React Tutorials - Day Three - Components

This is the third article of the React Tutorials series. Following are the links of my previous articles of this series.

Today, we will learn about components. Components are the heart of React, that let you split the UI into independent and reusable sections. In React, to create a component, we need to extend the “React.Component” class.

Example 

  1. import React from 'react';  
  2.   
  3. class Main extends React.Component {  
  4.    render() {  
  5.       return (  
  6.          <h2>  
  7.             Hello React!!!  
  8.          </h2>  
  9.       );  
  10.    }  
  11. }  
  12.   
  13. export default Main;   

Output

React

A component can have only one render function. The render function actually returns only one “html” element. If we try to return multiple HTML elements, we will get an error. Let's see with an example. Replace the “Mian.jsx” file code with the following code.

Main.jsx 

  1. import React from 'react';  
  2.   
  3. class Main extends React.Component {  
  4.    render() {  
  5.       return (  
  6.          <h2>  
  7.             Hello React!!!  
  8.          </h2>  
  9.           <h2>  
  10.             Hello React 2!!!  
  11.          </h2>  
  12.       );  
  13.    }  
  14. }  
  15.   
  16. export default Main;   

Output

React

So, we need to wrap both the HTML elements into one parent element.

Main.jsx 

  1. import React from 'react';  
  2.   
  3. class Main extends React.Component {  
  4.    render() {  
  5.       return (  
  6.           <div>  
  7.          <h2>  
  8.             Hello React!!!  
  9.          </h2>  
  10.           <h2>  
  11.             Hello React 2!!!  
  12.          </h2>  
  13.          </div>  
  14.       );  
  15.    }  
  16. }  
  17.   
  18. export default Main;   

Output

React

Let’s take another example of React.

Main.jsx 

  1. import React from 'react';  
  2.   
  3. class Main extends React.Component {  
  4.   constructor(){  
  5.     super();  
  6.     this.comment="This is new comment";  
  7.   }  
  8.    render() {  
  9.      var name="Pankaj Choudhary";  
  10.       return (  
  11.         <div>  
  12.          <h2>{name}</h2>  
  13.          <h2>{(function(){  
  14.            return "React";  
  15.            })()}</h2>   
  16.   
  17.            <h3>  
  18.              {this.comment}  
  19.            </h3>  
  20.          </div>  
  21.       );  
  22.    }  
  23. }  
  24.   
  25. export default Main;   

Output

React

In React, everything written into “{}” (curly braces) is treated as normal JavaScript code. So, we can use {} to write the JavaScript code in html.

Multiple Components

Let’s create another two components. First, create a “header.jsx” file into “header” folder and paste the following code into this file.

Header.jsx 

  1. import React from 'react';  
  2.   
  3. class Header extends React.Component {  
  4.     
  5.    render() {  
  6.       
  7.       return (  
  8.         <div>  
  9.         <h2>This is header</h2>  
  10.          </div>  
  11.       );  
  12.    }  
  13. }  
  14.   
  15. export default Header;  

Now, create “footer.jsx” file into “footer” folder and paste the following code into this file.

Footer.jsx

  1. import React from 'react';  
  2.   
  3. class Footer extends React.Component {  
  4.     
  5.    render() {  
  6.       
  7.       return (  
  8.         <div>  
  9.         <h2>This is footer</h2>  
  10.          </div>  
  11.       );  
  12.    }  
  13. }  
  14.   
  15. export default Footer;  

After creating all these files, the following will be the structure of our project.

React

Now, we will use both components into our “main” component. Below is the code for “main.jsx” file.

Main.jsx

  1. import React from 'react';  
  2. import Footer from '../footer/footer';  
  3. import Header from '../header/header';  
  4. class Main extends React.Component {  
  5.    render() {  
  6.       return (  
  7.           <div>  
  8.             <Header/>  
  9.          <h2>  
  10.             Hello React!!!  
  11.          </h2>  
  12.          <Footer/>  
  13.          </div>  
  14.       );  
  15.    }  
  16. }  
  17.   
  18. export default Main;  

In the above code, we imported the “Footer” and “Header” components, and used these in the template of “Main” component. After making all the changes, the following will be our output.

Output

React

We can render the component in whatever manner we want, for example - we can create unordered list(ul) of components. Let’s take an example. Now, replace the code of “main.jsx” file with the following.

Main.jsx

  1. import React from 'react';  
  2. import Footer from '../footer/footer';  
  3. import Header from '../header/header';  
  4. class Main extends React.Component {  
  5.    render() {  
  6.      var array=[  
  7.         <Header/>,  
  8.         <Footer/>,  
  9.         <Header/>,  
  10.         <Footer/> ,  
  11.         <Header/>,  
  12.         <Footer/>  
  13.      ];  
  14.       return (  
  15.           <div>  
  16.             <h2>React Example</h2>  
  17.             <ul>  
  18.               {array}  
  19.               </ul>  
  20.          </div>  
  21.       );  
  22.    }  
  23. }  
  24.   
  25. export default Main;  

Output

React

In the above example, we have created an array of “header” and “footer” components and printed this array into a “ul”.

Component Life Cycle

In React, each component has a lifecycle with several hooks in this lifecycle. We can use these hooks to perform some task at specific time of the component. Following are the methods called during the lifecycle of a component.

Constructor

This method is called before any other methods of the lifecycle, and creates an instance of component. You can use the constructor to initialize the state and properties for the component.

componentWillMount

This method is called before mounting and also runs before the render method. This is the only lifecycle hook that is called on the server rendering. You can use this method for server rendering tasks or configuration.

componentDidMount

This method is called after the first render only. If we need to load the data from remote server, then it is a good point to initialize the network request. We can use this method for any function that needs delayed execution using like setTimeout or setInterval.

componentWillReceiveProps

This method is called when a mounted component gets its properties. If we need to change the state in response of the props, then we can implement the logic of state change here. We can compare the this.props and nextProps; and on behalf of the comparison result, we can implement the state updates.

shouldComponentUpdate

This method is called before the render method and checks if it should re-render the component or not. React lifecycle has a simple fundamental that whenever state or props of the component is changed, it re-renders the component. So, if you want the component to not to re-render, then return false in this method. By default, it returns true.

componentWillUpdate

This method is called before the new state and props are rendered in component.

componentDidUpdate

This method is invoked after the updates are reflected.

componentWillUnmount

This method is called when component unmounts and is destroyed from the DOM. During the unmounting process, it  performs some tasks related to cleanup also.

Let’s take an example of different hooks of a component lifecycle. Replace the code of “header.jsx” with the following code.

Header.jsx 

  1. import React from 'react';  
  2.   
  3. class Header extends React.Component {  
  4.     
  5.   constructor(){  
  6.      super();  
  7.       console.log('constructor executed')  
  8.   }  
  9.   componentWillMount() {  
  10.       console.log('componentWillMount executed')  
  11.    }  
  12.   
  13.    componentDidMount() {  
  14.       console.log('componentDidMount executed')  
  15.    }  
  16.   
  17.    componentWillReceiveProps(newProps) {      
  18.       console.log('componentWillReceiveProps executed')  
  19.    }  
  20.   
  21.    shouldComponentUpdate(newProps, newState) {  
  22.     console.log('shouldComponentUpdate executed')  
  23.       return true;  
  24.    }  
  25.   
  26.    componentWillUpdate(nextProps, nextState) {  
  27.       console.log('componentWillUpdate executed');  
  28.    }  
  29.   
  30.    componentDidUpdate(prevProps, prevState) {  
  31.       console.log('componentDidUpdate executed')  
  32.    }  
  33.   
  34.    componentWillUnmount() {  
  35.       console.log('componentWillUnmount executed')  
  36.    }  
  37.    render() {  
  38.       
  39.       return (  
  40.         <div>  
  41.         <h2>This is header</h2>  
  42.         <h3>{this.props.random}</h3>  
  43.          </div>  
  44.       );  
  45.    }  
  46. }  
  47.   
  48. export default Header;  

Now, replace the code of “main.jsx” with the following code.

Main.jsx

  1. import React from 'react';  
  2. import Footer from '../footer/footer';  
  3. import Header from '../header/header';  
  4. class Main extends React.Component {  
  5.   constructor(){  
  6.      super();  
  7.     this.state = {  
  8.          random: (Math.random())*1000  
  9.       }  
  10.   
  11.       this.random = this.random.bind(this)  
  12.   }  
  13.   random() {  
  14.       this.setState({random: new Date()})  
  15.    }  
  16.   
  17.    render() {  
  18.           return (  
  19.           <div>  
  20.             <h2>React Example</h2>  
  21.             <button onClick = {this.random}>Change random</button>  
  22.             <Header time = {this.state.random}></Header>  
  23.          </div>  
  24.       );  
  25.    }  
  26. }  
  27.   
  28. export default Main;  

After making all the changes, we get the following output.

React
When we click on the “Change random” button, the props of the header component gets changed and we get the following result.

React
You can see that after making the changes in props of header.jsx, all the updated methods are executed in a sequence.

Conclusion

In this article, we learned about React components and component lifecycle. In our next article, we will learn about states and props. If you have any queries or doubts, please mention them in the comments section. You can download the latest source code of this project from GitHub. Given below is the link of repository.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now