Next.jsでのアニメーションとトランジション: 魅力的なインタラクション

本記事では、Next.jsのアニメーションとトランジションを使った魅力的なインタラクションの実装について解説します。以下の目次に沿って解説していきます。

目次

  1. はじめに
  2. CSSアニメーション
  3. React Springを使ったアニメーション
  4. Framer Motionを使ったアニメーション
  5. React Transition Groupを使ったトランジション
  6. Page Transitions
  7. まとめ

1. はじめに

Next.jsでアニメーションとトランジションを実装するには、CSSアニメーションやReact Springなどのライブラリを利用します。これらの技術を組み合わせることで、綺麗なインタラクションが実現できます。

2. CSSアニメーション

まずは、CSSアニメーションで簡単なインタラクションを実現してみましょう。以下のコード例では、ボタンがホバーされたときに拡大するアニメーションを行っています。

.button {
  transition: transform 0.3s;
}

.button:hover {
  transform: scale(1.1);
}

3. React Springを使ったアニメーション

React Springは、シンプルでパワフルなアニメーションライブラリです。以下に、React Springでボタンクリック時のアニメーションを作成する例を示します。

import React from 'react';
import { useSpring, animated } from 'react-spring';

function App() {
  const [style, set] = useSpring(() => ({ transform: 'scale(1)' }));

  return (
    <animated.button
      style={style}
      onClick={() => set({ transform: 'scale(1.1)' })}
    >
      Click me
    </animated.button>
  );
}

export default App;

4. Framer Motionを使ったアニメーション

Framer Motionは、Reactアプリケーションでアニメーションを簡単に実装できるライブラリです。以下に、Framer Motionでスムーズなマウスオーバーアニメーションを作成する例を示します。

import React from 'react';
import { motion } from 'framer-motion';

function App() {
  return (
    <motion.div
      whileHover={{ scale: 1.1 }}
      transition={{ duration: 0.3 }}
    >
      Hover me
    </motion.div>
  );
}

export default App;

5. React Transition Groupを使ったトランジション

React Transition Groupを使って、リストアイテムの追加や削除時にアニメーションを実装することができます。以下に、アイテム追加時のフェードインアニメーションを作成する例を示します。

import React from 'react';
import { TransitionGroup, CSSTransition } from 'react-transition-group';

function App() {
  // ...
  return (
    <TransitionGroup>
      {items.map(item => (
        <CSSTransition key={item.id} timeout={500} classNames="fade">
          <div>{item.name}</div>
        </CSSTransition>
      ))}
    </TransitionGroup>
  );
}

export default App;

6. Page Transitions

Next.jsでは、ページ遷移時にアニメーションを付けることができます。以下に、Framer Motionを使ったページ遷移アニメーションを作成する例を示します。

import { useRouter } from 'next/router';
import { AnimatePresence, motion } from 'framer-motion';

function MyApp({ Component, pageProps }) {
  const router = useRouter();

  return (
    <AnimatePresence exitBeforeEnter>
      <motion.div
        key={router.route}
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        exit={{ opacity: 0 }}
        transition={{ duration: 0.5 }}
      >
        <Component {...pageProps} />
      </motion.div>
    </AnimatePresence>
  );
}

export default MyApp;

7. まとめ

Next.jsで魅力的なアニメーションとトランジションを実装する方法を網羅的に説明しました。インタラクションを工夫することで、ユーザーフレンドリーなウェブアプリケーションを作成しましょう。