Search code examples
javascriptreactjssingle-page-applicationtypeerrorarrow-functions

Cannot read property 'setState' of null react


This code was given to me while answering another question, it works fine in Codepen. Original code

However when I try adapting it to my project, first of all, the arrow function is not recognized and I get the Unexpected token error at this arrow function:

getBtnId = (e) => {
    //code in here
};

So I changed it to a regular function, and now the component looks like this:

export default class HelpPage extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        panelIndex: 0
    };
    this.getBtnId.bind(this);
}

getBtnId (e) {
    if(e.target && e.target.nodeName == "BUTTON") {
        console.log(e.target);
        this.setState({
            panelIndex: Number(e.target.id)
        });
  }
  return e;
};

render() {
    return (
        <div className="container">
            <HelpMenu
                getBtnId={this.getBtnId}
            />
            <HelpPanels
                panelIndex={this.state.panelIndex}
            />
        </div>
    )
}

}

However now whenever I press one of the buttons I get the error

"Uncaught TypeError: Cannot read property 'setState' of null"

What can I do now to fix this?

Thanks!


Solution

  • Actually this.getBtnId.bind(this) do nothing !

    This will solve your problem :

    this.getBtnId = this.getBtnId.bind(this);