While redesigning Instagram Web from the inside out this year, we enjoyed using a number of ES6+ features to write our React components. Allow me to highlight some of the ways that these new language features can change the way you write a React app, making it easier and more fun than ever.
Classes
By far the most outwardly visible change to how we write React components using ES6+ comes about when we choose to use the class definition syntax. Instead of using the React.createClass
method to define a component, we can define a bonafide ES6 class that extends React.Component
:
class Photo extends React.Component {
render() {
return <img alt={this.props.caption} src={this.props.src} />;
}
}
Right away, you'll notice a subtle difference – a more terse syntax is available to you when defining classes:
// The ES5 way
var Photo = React.createClass({
handleDoubleTap: function(e) { … },
render: function() { … },
});
// The ES6+ way
class Photo extends React.Component {
handleDoubleTap(e) { … }
render() { … }
}
Notably, we've dropped two parentheses and a trailing semicolon, and for each method declared we omit a colon, a function
keyword, and a comma.
All of the lifecycle methods but one can be defined as you would expect when using the new class syntax. The class' constructor
now assumes the role previously filled by componentWillMount
:
// The ES5 way
var EmbedModal = React.createClass({
componentWillMount: function() { … },
});
// The ES6+ way
class EmbedModal extends React.Component {
constructor(props) {
super(props);
// Operations usually carried out in componentWillMount go here
}
}