In JavaScript, the value of this
changes depending on the current context. Within React class component methods, developers normally expect this to refer to the current instance of a component, so it is necessary to bind these methods to the instance. Normally this is done in the constructor—for example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class SubmitButton extends React.Component { constructor(props) { super(props); this.state = { isFormSubmitted: false }; this.handleSubmit = this.handleSubmit.bind(this); } handleSubmit() { this.setState({ isFormSubmitted: true }); } render() { return ( <button onClick={this.handleSubmit}>Submit</button> ) } } |
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.