1

I am trying to create toggle menu for my react app.

I am facing some issue with 'getInitialState()'. It's show error like:

Warning: getInitialState was defined on Header, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?*

Here is my code:

class Header extends Component {
  constructor(props){
    super(props);
  }
  getInitialState(){
    return {"showHideSidenav":"hidden"};
  }

  render() {
    return (
      <div className="header">
        <div className="toggle-btn" onClick={this.toggleSidenav.bind(this)}>
          <div>
            <span></span>
            <span></span>
            <span></span>
          </div>
          <span>Menu</span>
        </div>
        <div className={this.props.showHideSidenav} id="main-menu">
          <ul>
            <li>
               1
            </li>
            <li>
               2
            </li>
            <li>
               3
            </li>
            <li>
              4
            </li>
          </ul>
        </div>
      </div>
    )
  }
  toggleSidenav() {
    var css = (this.props.showHideSidenav === "hidden") ? "show" : "hidden";
    this.setState({"showHideSidenav":css});
  }
}

How I can I solve this?

Hiral
  • 77
  • 8
  • Yes, I have already imported – Hiral Aug 07 '19 at 07:44
  • Possible duplicate of [What is the difference between using constructor vs getInitialState in React / React Native?](https://stackoverflow.com/questions/30668326/what-is-the-difference-between-using-constructor-vs-getinitialstate-in-react-r) – RIYAJ KHAN Aug 07 '19 at 07:45
  • Read this https://reactjs.org/docs/react-without-es6.html#setting-the-initial-state – UtkarshPramodGupta Aug 07 '19 at 07:47
  • Try calling onClick={this.toggleSidenav.bind(this)} as onClick={(e)=> this.toggleSidenav(e)} – Thilina Koggalage Aug 07 '19 at 07:49
  • Seems this is a duplicated question: https://stackoverflow.com/questions/30720620/react-es6-getinitialstate-was-defined-on-a-plain-javascript-class Have you refer this? – Thilina Koggalage Aug 07 '19 at 07:50

1 Answers1

3

I think you can find an answer here -> React, ES6 - getInitialState was defined on a plain JavaScript class

As a summary:

If you use es6 class which extends React.Component you need to define the state in the constructor:

this.state = {...}

getInitialState() is used in the es5 React.createClass function.

Ovidiu G
  • 1,253
  • 5
  • 25
  • 47