Binding "this" in React
By David Reeder, 05 July 2024
You may well get the error "TypeError: Cannot read property of 'state' of undefined."
This could mean we need to bind our event handler in the constructor like so:
constructor(props){ super(props); this.myEventHandler = this.myEventHandler.bind(this) }
An alternative is to use an error function for your event handler. Arrow functions don't rescope the this keyword, so it avoids the need to bind this in the constructor as above:
state = { coolvalue: 'Dave you are cool' }; myEventHandler = () => { console.log('My cool value is: ", this.state.coolvalue); }
We can also use an inline arrow function in the render method:
render() { return (<button onClick={() => {this.myEventHandler({coolvalue: 'Dave you are cool'})} className="btn">Click Me</button>); }