Skip to content

Instantly share code, notes, and snippets.

@sivadass
Created November 30, 2017 09:14
Show Gist options
  • Save sivadass/3b2447bbd348e4324b912eadb4cea1c6 to your computer and use it in GitHub Desktop.
Save sivadass/3b2447bbd348e4324b912eadb4cea1c6 to your computer and use it in GitHub Desktop.
Bind methods in React Components
// 1.Bind in constructor
class A extends React.Component {
constructor(props) {
super(props)
this._eventHandler = this._eventHandler.bind(this)
}
_eventHandler() {
// ...
}
render() {
return <div onClick={this._eventHandler} />
}
}
// 2.Arrow function in render()
class A extends React.Component {
_eventHandler() {
// ...
}
render() {
return <div onClick={()=>{this._eventHandler()}} />
}
}
// 3. bind in render()
class A extends React.Component {
_eventHandler() {
// ...
}
render() {
return <div onClick={this._eventHandler.bind(this)} />
}
}
// 4. ES2015 arrow function in class fields
class A extends React.Component {
_eventHandler = () => {
// ...
}
render() {
return <div onClick={this._eventHandler} />
}
}
// 5. @autobind decorator
class A extends React.Component {
@autobind
_eventHandler() {
// ...
}
render() {
return <div onClick={this._eventHandler} />
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment