React is a client side scripting language developed by Facebook for handling the view layer of web application and mobile application. It contains simple component based architecture in which components are small unit used in representing data. These UI components are reusable and can be called multiple times.
var HelloMessage = React.createClass({
render: function() {
return <h1>Hello {this.props.name}</h1>;
}
});
ReactDOM.render(
<HelloMessage name=”myname” />,
document.getElementById(‘example’)
);
Here in above example of simple react component where React.createClass method is used to generate a component class HelloMessage. <HelloMessage /> Instance component class and output information.
Things to know:- Keep your component small because every good developer knows smaller class or module are easy to understand, test and maintain.
React sees component as a State Machine and through this it interacts with the user to achieve a different state, rendering UI, user interface and data consistency.
React simply update the state of component and re-render the user interface based on this new state. Here is an example:-
var LikeButton = React.createClass({
getInitialState: function() {
return {liked: false};
},
handleClick: function(event) {
this.setState({liked: !this.state.liked});
},
render: function() {
var text = this.state.liked ? ‘on’ : ‘off’;
return (
<p onClick={this.handleClick}>
switch <b>{text}</b>
</p>
);
}
});
ReactDOM.render(
<LikeButton />,
document.getElementById(‘example’)
);
The above example creates a LikeButton component, the getInitialState method is used to define initial state, i.e. an object that can be read via this state property. When user clicks on the component, it results in status changes, this.setState method modifies the status value, on each modification it automatically calls this render method, rendering the component again.
The main difference between state and props is that props are immutable and state can change based on user interaction. This is why some container components need to define state to update and modify data. Subcomponents can only pass data through props.
The following example demonstrates how to use props in a component:
var HelloMessage = React.createClass({
render: function() {
return <h1>Hello {this.props.name}</h1>;
}
});
ReactDOM.render(
<HelloMessage name=”myname” />,
document.getElementById(‘example’)
);
The React Component lifecycle can be divided into three states:
Various Component lifecycle methods are:
componentWillMount, componentDidMount, componentWillReceiveProps, shouldComponentUpdate, componentWillUpdate etc.
Following is a complete example of component life cycle methods.
var Button = React.createClass({
getInitialState: function() {
return {
data:0
};
},
setNewNumber: function() {
this.setState({data: this.state.data + 1})
},
render: function () {
return (
<div>
<button onClick = {this.setNewNumber}>INCREMENT</button>
<Content myNumber = {this.state.data}></Content>
</div>
);
}
})
var Content = React.createClass({
componentWillMount:function() {
console.log(‘called before rendering’)
},
componentDidMount:function() {
console.log(‘Called after the first render’)
},
componentWillReceiveProps:function(newProps) {
console.log(‘called when the component receives a new prop’)
},
shouldComponentUpdate:function(newProps, newState) {
return true;
},
componentWillUpdate:function(nextProps, nextState) {
console.log(‘called when the component has received a new props or state’);
},
componentDidUpdate:function(prevProps, prevState) {
console.log(‘Called immediately after the component has completed its update’)
},
componentWillUnmount:function() {
console.log(‘called as soon as the component is removed from the DOM’)
},
render: function () {
return (
<div>
<h3>{this.props.myNumber}</h3>
</div>
);
}
});
ReactDOM.render(
<div>
<Button />
</div>,
document.getElementById(‘example’)
);
In this example, simple increment button is created to increment number count. For a detailed description of these methods, you can refer to the react official doc.
“Something you should know about”
For stateless components in react js, which is useful when we need less coding in our react js project. These components use plain javascript code.
Left side shows the simple helloWorld component and right is showing stateless component.
Now let’s see what’s going on in these two piece of code. Let’s look at left example first, in this simple react component in which name property is showing on click event of link. Here everything looks like simple view component of react as we discussed earlier.
Now if we look at right side of example, what’s going on there??
Here are some key points of stateless component for better understanding:
onClick={this.sayHi.bind(this)}>Say Hi</a>
onClick={sayHi}>Say Hi</a>
as if there is no need of class in stateless component results in removal of reference variable, this is used for binding the data. It’s a great achievement in removal of annoying javascript keywords. By dumping the class, there is no need of binding data which in turn starts using this as stateless components which starts behaving like a function.
Yes here are some downsides:
<TextInput
label=’email’
inputName=’txtInput’
ariaLabel=’email’
validation={this.state.errors}
ref={r => this._emailAddress = r}
/>
If we make <TextInput as a stateless component then we can’t pass refs in it. The idea of stateless is that there isn’t an instance created for it (state). As such, you can’t attach a ref, since there’s no state to attach the ref with.
This piece of code will throw warning.
Stateless function components cannot be given refs. Attempts to access this ref will fail.
That’s it! Hopefully, this will give you a bit of a head-start on React and help you avoid some of the most common mistakes. For any further discussion or doubts, you can get in touch with us at info@mindrops.com