2

I need to access the window object in my react component to get something from the query string. This is what my component looks like:

export function MyComponent() {
  return (
    <div>
      Display the qs: {(window && window.location.search) || 'nothing'}
    </div>
  )
}

This is all fine and well if I run the app and then visit the page where I need to access the window, but if I start the app on the page I need the window, I get the following error:

ReferenceError: window is not defined

Most the solutions I see so far make use of the componentWillMount to solve the issue. So my question is, how do I solve this issue in the functional component? Or what is the best way to do so without using the lifecycle methods?

Not sure if this is relevant but I am using NextJS as well.

theJuls
  • 6,788
  • 14
  • 73
  • 160

2 Answers2

5

Refer to Next.js wiki

Next.js is universal, which means it executes code first server-side, then client-side. The window object is only present client-side, so if you absolutely need to have access to it in some React component, you should put that code in componentDidMount. This lifecycle method will only be executed on the client. You may also want to check if there isn't some alternative universal library which may suit your needs.

export function MyComponent() {
  const isAvailable = useRef(false);

  useEffect(() => {
    isAvailable.current = typeof window !== "undefined" && window.location.search;
  }, []);

  return <div>Display the qs: {isAvailable.current || 'nothing'}</div>;
}
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
3
const isWindowContext = typeof window !== "undefined";

export function MyComponent() {
  const search = isWindowContext && window.location.search;
  return <div>Display the qs: {search || 'nothing'}</div>;
}
Olivier Boissé
  • 15,834
  • 6
  • 38
  • 56