Why can’t I access state and props inside event handler?
As of React .14 event handlers are not being auto-bound to the scope of the component. You can use the dirty .bind(this) method which I hate and it’s slow like so.
1 2 3 4 5 6 | render() { var optionNodes = this.state.items.map((item) => { return(<option key={item.id} value={item.val}>{item.val}</option>) }); return(<div><select onChange={this.onSelectionChange.bind(this)} defaultValue={this.state.currentItem}>{optionNodes}</select></div>); } |
Or use fat arrow functions to wrap the callback in, this is much faster and does not require binding scope since fat arrow function execute on the scope the where created.
1 2 3 4 5 6 | render() { var optionNodes = this.state.items.map((item) => { return(<option key={item.id} value={item.val}>{item.val}</option>) }); return(<div><select onChange={(event) => { this.onSelectionChange(event) }} defaultValue={this.state.currentItem}>{optionNodes}</select></div>); } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.