javascriptreactjsfbjs

Getting window is not defined on ReactJs


I am getting the error: "ReferenceError: window is not defined" on React.

Below is my code:

import React from 'react';
import styles from './Header.css';
import withStyles from '../../decorators/withStyles';
import Link from '../../utils/Link';
import SignInMenu from './SignInMenu';
import UserMenu from './UserMenu';
import Navigation from '../Navigation';
import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment';

@withStyles(styles)
class Header extends React.Component {

  constructor() {
    super();
    return {
      windowWidth: 0,
      windowHeight: 0
    };
  }

  componentDidMount() {
    this.setState({
      windowWidth: window.innerWidth,
      windowHeight: window.innerHeight
    });
  }

  render() {
     let windowWidth = this.state.windowWidth;
     let windowHeight = this.state.windowHeight;

     if (windowWidth < 1000) {
       let header = (<div>mobile</div>);
     }  else {
       let header = (<div>desktop</div>);
    }
  }

I am trying to render different views for desktop and mobile and am just starting out with React. I am not sure if I am doing this right, was following some guides online and got stuck here. Any ideas on what I am doing wrong? Thanks


Solution

  • Your problem may be in your constructor.

        constructor() {
          super();
          this.state = {
            windowWidth: 0,
            windowHeight: 0
          };
        }