DEV Community

Sina
Sina

Posted on

Using Client-side Javascript Librarys with Next.js

So, the other day I was trying to integrate wow.js in a next.js Application for smooth onScroll Animations. It turned out: that’s not as trivial as I thought it would be, as wow.js is executed on the Client-side (as it needs the window attribute) and Next.js is famous for being Server-side rendered (SSR) React Code. Or to be precise, it’s not that difficult if you know how it works.

That is to say, instead of the usual import on the top-level, you have to require the Library inside of the componentDidMount function, which is only executed in the client.

componentDidMount() {

  if(typeof window !== 'undefined') {

    window.WOW = require('wowjs');

  }

  new WOW.WOW().init();

}

After importing it this way, you can use wowJS the usual way via classNames:

<div className="wow fadeInUp" data-wow-offset="20">

  <h1>My awesome animated Component</h1>

</div>

Good to know: wow.js needs to be rendered only once per View. For example, if you have a few Components that you want to animate, you can require wow.js in a wrapper Component. That way it’s only loaded once.

Good to think about too: if there is one for your use case, consider using an react-alternative instead of this workaround.

Top comments (3)

Collapse
 
f2aldi profile image
Aldi • Edited

i am trying this to my NextJS but still getting error "window is not defined"
its this tutorial still Work? Its this right to import Wow JS to Next JS? Thanks

dev-to-uploads.s3.amazonaws.com/i/...

Collapse
 
chpokmankg profile image
ChpokmanKG

Did you find the solve?

Collapse
 
chpokmankg profile image
ChpokmanKG

It doesn't work for me