jperasmus / nextjs-page-transition-example

Example repo for https://jperasmus.me/posts/page-transitions-for-nextjs
2 stars 7 forks source link

Custom Animation #1

Open jonrrivera opened 3 years ago

jonrrivera commented 3 years ago

Hi,

thanks for the great tutorial. I got everything working but currently struggling adding my own custom animation. How would I go about doing that? Here is my _app.js component.

export default function App({ Component, pageProps, router }) {
    console.log(router.asPath);
    return (
        <>
            <Flipper flipKey={router.asPath}>
                <Flipped flipId="this">
                    <div className={router.asPath ? "full" : "square"} >
                        <Component {...pageProps} />
                    </div>
                </Flipped>
            </Flipper>
        </>
    )
}
jperasmus commented 3 years ago

Hi @jonrrivera I'm glad you found the tutorial useful.

Honestly, I do not think the FLIP animation technique is the best for elaborate custom page transitions. The whole idea with FLIP is to take the state of something before and after a change, but before rendering the after state, you set it back to the before state and then release it to animate into the new state with opacity and transform transitions.

I have not tried a more complex page transition with FLIP before, but theoretically, you would need to inverse the page transition before exit and then let the FLIP animation transition the new page in.

Something I can think of right now that you could experiment with is using the Next.js router events to determine when a route is about to change so that you can apply the inverse effect (maybe pass a CSS class through to the page, etc)

In your custom _app.tsx you can add something like this:

const router = useRouter()

  useEffect(() => {
    const handleRouteChange = (url) => {
      // perhaps set some state here
    }

    router.events.on('routeChangeStart', handleRouteChange)

    // If the component is unmounted, unsubscribe
    // from the event with the `off` method:
    return () => {
      router.events.off('routeChangeStart', handleRouteChange)
    }
  }, [])

You can read more about the Next.js router events here.

If you end up figuring something cool out, I would love to hear about it 😄