Function Bindings
<div onClick={this.handleClick} />
What’s wrong with that? If you’re not using React.createClass
, which autobinds functions, you need to do it yourself. The correct way would be add it to constructor:
import React from 'react'
export default class ComponentName extends React.Component {
constructor(){
super()
this.handleClick = this.handleClick.bind(this)
}
...
Another way of dealing with this is by enabling stage 0 in babel to include es7 classProperties
Warning Use with extreme caution. Since this is Stage 0 - Strawman. This is subject to change in the future and may require a bit of rewrite of your code.
The idea is to combine fat arrow syntax which automatically binds to this. A more detailed explanation can be found here
export default class ComponentName extends React.Component {
...
handleClick = (e) => {
...
}
It may seem tempting to use handler.bind(this)
or the ES7 ::
handler syntax to bind handlers in the component’s render()
method. However, this may break the optimization of the PureRenderMixin
and will create a new function every time the render()
method is called.
export default class ComponentName extends React.Component {
handleClick(e) {
...
}
render(){
return (
// this will create a new function every
// time the render method is called
<button onClick={::this.handleClick}> click </button>
);
}
}
Static Property Initializers
In old-school components, you can do this at the start of your component:
propTypes: {
field: React.PropTypes.string
}
In ES6/7 components, you have two options, you can specify them after your component class, like so:
Component.propTypes = {
//prop validations
}
Which works fine, but I think doing this is a lot better:
class Test extends React.Component{
static propTypes = {
//validate here
}
render(){
//return
}
}
What’s the “gotcha” you might ask? You need to enable stage 0 babel transforms to use this.
Have more examples that you would like to add? Please add on to this post by sending a pull request!