18

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)?

6 Answers 6

23

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the tip! Placing the window. in componentDidMount fixed the issue :)
6

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.

Comments

3

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).

1 Comment

In one instance, I needed to do new Audio(), and I need to check if window and window.Audio exists. Sadly, if I do it in componentDidMount(), it comes up as undefined in the props of the child module I put it in even if I do it onClick.
1

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

Comments

0
<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

2 Comments

Just dropping a piece of code is rarely helpful. Please add an explanation.
While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
0

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.

1 Comment

Welcome to SO. Please add some context to your answer. What lifecycle hook and why?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.