Kevin Ghadyani
Kevin Ghadyani

Reputation: 7307

Error `window not defined` in Node.js

I know window doesn't exist in Node.js, but I'm using React and the same code on both client and server. Any method I use to check if window exists nets me:

Uncaught ReferenceError: window is not defined

How do I get around the fact that I can't do window && window.scroll(0, 0)?

Upvotes: 18

Views: 33044

Answers (6)

Jeff Diederiks
Jeff Diederiks

Reputation: 1380

Sawtaytoes has got it. I would run whatever code you have in componentDidMount() and surround it with:

if (typeof window !== 'undefined') {
  // code here
}

If the window object is still not being created by the time React renders the component, you can always run your code a fraction of a second after the component renders (and the window object has definitely been created by then) so the user can't tell the difference.

if (typeof window !== 'undefined') {
    var timer = setTimeout(function() {
        // code here
    }, 200);
}

I would advise against putting state in the setTimeout.

Upvotes: 23

JustAnotherGirl
JustAnotherGirl

Reputation: 371

Move the window and related code to the mounted() lifecycle hook. This is because mounted() hook is called on the client side only and window is available there.

Upvotes: 0

Peter Lazzarino
Peter Lazzarino

Reputation: 11

This is a little older but for ES6 style react component classes you can use this class decorator I created as a drop in solution for defining components that should only render on the client side. I like it better than dropping window checks in everywhere.

import { clientOnly } from 'client-component';

@clientOnly
class ComponentThatAccessesWindowThatIsNotSafeForServerRendering extends Component {
    render() {
        const currentLocation = window.location;
        return (
            <div>{currentLocation}</div>
        )
    };
}

https://github.com/peterlazzarino/client-component

Upvotes: 1

Andrei  Fyodorov
Andrei Fyodorov

Reputation: 23

<Router onUpdate={() => window.scrollTo(0, 0)} history= {browserHistory}>

if you need to open new page on top in React JS app, use this code in router.js

Upvotes: 0

Kevin Ghadyani
Kevin Ghadyani

Reputation: 7307

This will settle that issue for you:

typeof(window) === 'undefined'

Even if a variable isn't defined, you can use typeof() to check for it.

Upvotes: 6

topheman
topheman

Reputation: 7922

This kind of code shouldn't even be running on the server, it should be inside some componentDidMount (see doc) hook, which is only invoke client side. This is because it doesn't make sense to scroll the window server side.

However, if you have to reference to window in a part of your code that really runs both client and server, use global instead (which represents the global scope - e.g. window on the client).

Upvotes: 3

Related Questions