Created
September 13, 2019 15:17
-
-
Save stoneboyindc/f09b604a65e70cbcb2e52ce4688f1613 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Method 1: Using `bind()` method / Constructor bind | |
class Toggle extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = {isToggleOn: true}; | |
// This binding is necessary to make `this` work in the callback | |
this.handleClick = this.handleClick.bind(this); | |
} | |
handleClick() { | |
this.setState(state => ({ | |
isToggleOn: !state.isToggleOn | |
})); | |
} | |
render() { | |
return ( | |
<button onClick={this.handleClick}> | |
{this.state.isToggleOn ? 'ON' : 'OFF'} | |
</button> | |
); | |
} | |
} | |
ReactDOM.render( | |
<Toggle />, | |
document.getElementById('root') | |
); | |
Method 2: Arrow function in JSX / Using arrow function in the declaration of event handler | |
If calling bind annoys you, there are two ways you can get around this. If you are using the experimental public class fields syntax, you can use class fields to correctly bind callbacks: | |
class LoggingButton extends React.Component { | |
// This syntax ensures `this` is bound within handleClick. | |
// Warning: this is *experimental* syntax. | |
handleClick = () => { | |
console.log('this is:', this); | |
} | |
render() { | |
return ( | |
<button onClick={this.handleClick}> | |
Click me | |
</button> | |
); | |
} | |
} | |
Method 3: Arrow function class method / Use arrow function in the registration of event handler | |
If you aren’t using class fields syntax, you can use an arrow function in the callback: | |
class LoggingButton extends React.Component { | |
handleClick() { | |
console.log('this is:', this); | |
} | |
render() { | |
// This syntax ensures `this` is bound within handleClick | |
return ( | |
<button onClick={(e) => this.handleClick(e)}> | |
Click me | |
</button> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment