Dadnanmaga
Dadnanmaga

Reputation: 17

How to add transistion animation whenever the route is changed in next.js?

I have 2 links in the home page. I need different transition animation for each of these links.

i.e if i click the link button in the left. The transition should start from the left to right with the route change.

Upvotes: 1

Views: 1745

Answers (2)

Saajan
Saajan

Reputation: 680

You can use framer-motion and wrap the Linked Layout of the page component.

i.e

   import { motion } from 'framer-motion';

   <motion.div initial="exit" animate="enter" exit="exit">
      <motion.div variants={variants}>
        <Layout>
          ...
        </Layout>
      </motion.div>
    </motion.div>

This will animate the landing page onload.

Upvotes: 1

83C10
83C10

Reputation: 1212

In a nutshell, don't use Next.js's native <Link> tags, but regular <a> with custom event handlers to navigate your page. The event handlers should apply appropriate CSS class to page component to trigger the animation and redirect once the animation has finished. And since you're using Next.js don't forget to manually prefetch your routes!

Start with a simple <a> tag:

<a onClick={redirectToPageB}>Go to page B</a>`

Handle it with a function adding a CSS class to the page container and change your route after 1 second timeout:

const router = useRouter();

function redirectToPageB() {
  document.querySelector('#container').classList.add(styles.transitionRight);
  setTimeout(() => {
    router.push('/page-b');
  }, 1000);
}

And lastly, optimize by prefetching the /page-b route:

useEffect(() => {
  router.prefetch('/page-b');
}, []);

Upvotes: 1

Related Questions