버전: Next.js 14
타입스크립트 사용 x
npm install framer-motion
template은 레이아웃과 유사하게 자식 레이아웃이나 페이지를 감싸는 역할을 한다. layout과 다른 점은 탐색할 때, 자식 요소마다 새로운 인스턴스를 생성한다는 것이다.
import { motion } from "framer-motion";
import { usePathname } from "next/navigation";
export default function Transition({ children }) {
const path = usePathname();
return (
<motion.div
key={path}
initial={{ x: 1, y: 10, opacity: 0 }}
animate={{ x: 0, y: 0, opacity: 1 }}
transition={{ ease: "linear", duration: 0.5 }}
>
{children}
</motion.div>
);
}
app 하위 경로에 저장해야 한다.
app/template.jsx
template.jsx에 적기만 했는데 모든 페이지에 애니메이션이 적용돼서 신기했다... Next 짱!!
처음에 template.jsx에 위 코드를 적었을 때는 바로 적용이 안 됐다. 그래서 아래와 같은 방법을 사용했더니 애니메이션이 적용됐다. 한 10분~20분 정도 지나니까 이 코드가 없어도 template.jsx가 적용이 됐는데 이유는 모르겠다.
먼저 transition.jsx를 만든다. (이름은 본인 마음)
import { motion } from "framer-motion";
import { usePathname } from "next/navigation";
export default function Transition({ children }) {
const path = usePathname();
return (
<motion.div
key={path}
initial={animate.initial}
animate={animate.animate}
exit={animate.exit}
>
{children}
</motion.div>
);
}
const animate = {
initial: {
opacity: 0,
transition: `opacity 1s ease`,
},
animate: {
opacity: 1,
transition: `opacity 3s ease`,
},
exit: {
opacity: 0,
transition: `opacity 3s ease`,
},
};
app/layout.jsx에서 이 transition.jsx를 import해서 사용한다.
import Header from "./components/header"; //
import Transition from "./transition";
import "./globals.css";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<div className="container">
<Transition>{children}</Transition>
</div>
</body>
</html>
);
}
이런 식으로 했더니 페이지 전환 애니메이션이 적용됐다.
https://www.youtube.com/watch?v=jVU3JD6qOBo
https://juni-official.tistory.com/201
https://blog.stackademic.com/next-js-13-framer-motion-page-transitions-b2d58658410a
https://www.framer.com/motion/transition/