How to implement scroll-triggered animations in Next.js 13?

1.5k Views Asked by At

I am wondering how to implement scroll-triggered animations in Next.Js 13 properly.

I have tried to use a scroll-triggered animation library like AOS, but in order for it to work, it needs to be initialized inside a useEffect hook, which requires client-side rendering. Now all of that would be ok, if I was only using it for one component (and only for that component declaring client-side rendering via 'use client'), but that is not an option, since I want to make AOS accessible across my whole application, so that all components and parts of the page can consume it, and that, therefore, means, if Im getting this right, that everything would use client-side rendering (since I am declaring at the root (in order to be able to use useEffect)), which is not what I want.

Is there a better way of implementing this or am I just understanding this all the wrong way? I am new to Next.Js so I'm sorry if this question is more on the 'stupid' side, but I couldn't find, or figure out an answer so I decided to ask it over here. I will be happy to hear your answers. :)

2

There are 2 best solutions below

0
yorme On

I was able to make it work by doing this:

  1. Created a reusable component named AOS.jsx as below:
import { useEffect } from 'react';

import AOS from "aos";
import "aos/dist/aos.css";

export default function AOSComponent({
    children,
}: {
    children: React.ReactNode
}) {
    useEffect(() => {
        AOS.init()
    }, [])

    return <>{children}</>
}
  1. On each page 'client' where I need the AOS features, I wrap the page elements within it as below:

'use client'
...
import AOSComponent from '@/components/AOS';

export default function Home() {
  return (
    <AOSComponent>
      <div>
        Homepage
      </div>
    </AOSComponent>
  )
}
0
ABU SAID On

For server-side rendering with the App directory, you can create a reusable client component for AOS and render the server component as children. Remember that, we use NextJS for server side rendering.

  1. AOS client component:
'use client'
import { useEffect } from 'react';

import AOS from "aos";
import "aos/dist/aos.css";

export default function AOSComponent({
   children,
}: {
   children: React.ReactNode
}) {
   useEffect(() => {
       AOS.init()
   }, [])

   return <>{children}</>
}

Now, you can use this component as a parent of any server component, and you don't have to create every page as a client component.

  1. use the AOSComponent with a server component.
import AOSComponent from '@/components/AOS';

export default function Home() {
 return (
   <AOSComponent>
     <div>
       This component will render on the server!
     </div>
   </AOSComponent>
 )
}