React.js: Component Definition Cheatsheet
Let’s start with examples. If you want to create a React component which displays a greeting message along with a dynamic input name. We can do
var HelloMessage = React.createClass({
render: function(){
return <div>Hello {this.props.name}</div>;
}
});
In this example, we create a React component which would render a <div /> with a message “Hello [name]”. It can be used like this
ReactDOM.render(<HelloMessage name=”Sebastian” />, mountNode);
Definition using ES6 classes
We can write the same component with some syntactic sugar of ES6 classes. We can create new components by extending from React.Component class instead of React.createClass method.
class HelloMessage extends React.Component {
render() {
return <div>Hello {this.props.name}</div>;
}
}
Stateless Functional Components
Many times, with presentational components, you don’t need the lifecycle methods and your component just needs a render() method. Such components can be defined as pure functions which are called as Stateless Functional Components in React.
ES5 implementation of stateless functional components
In this example below, HelloMessage is a function which receives props and returns a React element.
var HelloMessage = function(props){
return <div>Hello {props.name}</div>;
}
ES6 implementation of stateless functional components
You can save some typing by the use of ES6 arrow functions like this
const HelloMessage = (props) => {
<div>Hello {props.name}</div>;
}
If you want to consume only specific named properties from the props object, you can use destructing assignment syntax of ES6 like
const HelloMessage = ({name}) => (
<div>Hello {name}</div>
);
Notice how we have taken out the “name” property from the receiving props argument.
Or just a one-liner arrow function
const HelloMessage = ({name}) => <div>Hello {name}</div>
Sweet! Isn’t it?
You can always define propTypes. For the purpose of simplicity it hasn’t been used and explained in the article. Some info from the React Official docs
These components (stateless functional components) behave just like a React class with only a render method defined. Since no component instance is created for a functional component, any ref added to one will evaluate to null. Functional components do not have lifecycle methods, but you can set .propTypes and .defaultProps as properties on the function.
Which one to use?
I recommend using beautiful ES6 syntaxes. If components don’t need any life-cycle methods, go ahead with ES6 arrow functions else use ES6 classes.
—
I am Sanket. If you liked the article, please recommend it. You can follow me to receive future updates about React, React Native, NativeBase and related technologies.