"Escaping" Next.js to access the browser

cassidoo

Cassidy Williams

Posted on December 4, 2020

"Escaping" Next.js to access the browser

Welcome to Blogvent, day 4!

Often when you are trying to add event listeners or DOM variables outside of a Next.js application, you’ll get a particularly unhelpful error:

ReferenceError: window is not defined
Enter fullscreen mode Exit fullscreen mode

To get around this, you can use the React hook, useEffect! There’s a couple options depending on what you need.

If you just need to access the window, you can use useEffect by itself, in something like this:

import { useEffect } from 'react'

function Page() {
  useEffect(() => {
    // use/set the window variable in here
  })
  ...
}
Enter fullscreen mode Exit fullscreen mode

And if you need to get an object in the browser (a DOM node or something) outside of Next.js, and render something into it, you can combine useEffect with useRef!

import ReactDOM from 'react-dom';
import { useRef, useEffect } from 'react'

function Page() {
  let ref = useRef()

  useEffect(() => {
    ReactDOM.render(<OtherThing/> ref.current);
  }, [])

  return <div ref={ref}/>
}
Enter fullscreen mode Exit fullscreen mode

I can’t think of a use case for this!

That’s okay! It’s something that comes up for very specific cases of “escaping” Next.js (or even Gatsby or vanilla React projects), for example using event listeners, using external JavaScript libraries, or adding certain animations. If you’d like to see an example in a real codebase, check out this part of the Activity Graph in Jamstack Explorers.

Speaking of which, if you’d like to learn more about Next.js, check out the course (with more to come) on Jamstack Explorers!

💖 💪 🙅 🚩
cassidoo
Cassidy Williams

Posted on December 4, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related