theJuls theJuls - 1 month ago 16
React JSX Question

Cannot reac 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 into 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 "Uncaught TypeError: Cannot read property 'setState' of null"

What can I do now to fix this?

Thanks!

Answer

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

This will solve your problem :

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