Webpack rendering: "window is not defined"

2.2k Views Asked by At

I use MERN – https://github.com/Hashnode/mern-starter (react, redux, webpack, nodejs, express) And component react-sound – https://github.com/leoasis/react-sound

When I include component

import Sound from 'react-sound';

and try start the server, I have "window is not defined" error from webpack server rendering.

But if I comment this line and start the server, all will be fine. After that I can uncomment this line and component will be work, because when the server is running, changes don't triggered server rendering (only front rendering).

If I try

if (typeof window !== 'undefined') {
    const Sound = require('react-sound');
}

And in render

render() {
    return (
        <div>
            <Sound playStatus={Sound.status.STOPPED} url="" />
        </div>
    );
}

I have ReferenceError: Sound is not defined error on front rendering (after webpack).

UPDATE:

If I try (var, not const)

if (typeof window !== 'undefined') {
    var Sound = require('react-sound');
}

I have TypeError: Cannot read property 'status' of undefined error on front rendering.

1

There are 1 best solutions below

4
dgrijuela On

Seems that you can't use react-sound outside of a browser environment.

The solution can be as follows:

let SoundEl;
if (typeof window !== 'undefined') {
  import Sound from 'react-sound';
  SoundEl = <Sound playStatus={Sound.status.STOPPED} url="" />
} else {
  SoundEl = <div></div>
}

...

render() {
  return (
    <div>
      {SoundEl}
    </div>
  )
}