I came across a couple of useful tricks when creating React components using the ES6 class syntax today - take a look at this example:
import React from 'react';
export default class Form extends React.Component {
// declare default state - doesn't need to be in constructor
// ES6+ only - property initialisers
state = {
hasChanged: false
};
constructor() {
super();
}
// arrow function binds 'this' so it can be called from event
// otherwise you'd need to have `this.formChanged = this.formChanged.bind(this)`
// in constructor (otherwise `this.setState` doesn't exist)
formChanged = () => this.setState({ hasChanged: true })
render() {
return (
<form onChange={ this.formChanged }>
<label>hello</label>
<input type="text" />
</form>
);
}
}
export default
you can choose to export multiple things (functions, classes, variables etc) from ES6 classes, but one must be default so the compiler knows what to do with `import`. More on this here.
class Form extends React.Component
you can extend React.Component
as a class, rather than use the React.createClass
function.
Class properties
state = {
hasChanged: false
};
State can be a class property, so you don't have to have this.state = {}
in the constructor
. This is an ES7 feature, so you'll need to include stage-0
in Babel, but is much more convenient than writing a lot of boilerplate.
Arrow functions
formChanged = () => this.setState({ hasChanged: true })
is an arrow function since it saves more boilerplate by binding this
. Otherwise, this would need a function declaration as well as a line in the constructor to bind this
, since the function is called from an event (so the context would be window
, which doesn't have the setState
function).