React Tutorials - Day Four - Props And State

This is the fourth article of the React Tutorials series. The list of the previous articles is given below.

Today, we will learn about the Props and State in React. Props and State are used to store and follow the data in applications. In previous articles, we learned about multiple components, so if we are using the multiple components in our application, then sometimes we need to share the data between components. In such type of scenarios, we can use Props. Actually, Props are used to transfer the data from parent to child component. Let’s look at an example and learn how Props work.

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.       
  8.   }  
  9.     
  10.   
  11.    render() {  
  12.      var employee={  
  13.        name:"Pankaj",  
  14.        project:"Lions Services",  
  15.        duration:"8 Months"  
  16.      }  
  17.           return (  
  18.           <div>  
  19.            <h3>This is main Component</h3>  
  20.            <Header empdetails={employee}></Header>  
  21.          </div>  
  22.       );  
  23.    }  
  24. }  
  25.   
  26. export default Main;   

header.jsx 

  1. import React from 'react';  
  2.   
  3. class Header extends React.Component {  
  4.     
  5.   constructor(){  
  6.      super();  
  7.   }  
  8.     
  9.    render() {  
  10.       
  11.       return (  
  12.         <div>  
  13.         <h2>This is header</h2>  
  14.         <h3> Employee: {this.props.empdetails.name}</h3>  
  15.         <h3> Project Name: {this.props.empdetails.project}</h3>  
  16.         <h3> Time Duration: {this.props.empdetails.duration}</h3>  
  17.          </div>  
  18.       );  
  19.    }  
  20. }  
  21.   
  22. export default Header;   

Output

React
To use a Property in component, just define the Property as an html attribute and assign the value to Props using “{}” curly braces.

React
In child component, we can access the Props value using the “this.props” keyword.

React

Default Props

In React, we can also define the default props for the component. Paste the following code into your “header.jsx” file and save the changes.

Header.jsx 

  1. import React from 'react';  
  2.   
  3. class Header extends React.Component {  
  4.     
  5.   constructor(){  
  6.      super();  
  7.   }  
  8.     
  9.    render() {  
  10.       
  11.       return (  
  12.         <div>  
  13.         <h2>This is header</h2>  
  14.         <h3> Employee: {this.props.empdetails.name}</h3>  
  15.         <h3> Project Name: {this.props.empdetails.project}</h3>  
  16.         <h3> Time Duration: {this.props.empdetails.duration}</h3>  
  17.         <ul>  
  18.             {this.props.skills.map((skill,i)=><li key={i}>{skill}</li>)}  
  19.         </ul>  
  20.          </div>  
  21.       );  
  22.    }  
  23. }  
  24.   
  25.   
  26. export default Header;   

When you save the change, you will get the following error.

React

We get this error because in “Header.jsx”, we don’t have any “skills” Prop. In React, we can define the default Props so if we forget to assign the value of Props from the parent component, it will use the default values for the Props. Now, replace the code of “Header.jsx” with the following code. 

  1. import React from 'react';  
  2.   
  3. class Header extends React.Component {  
  4.     
  5.   constructor(){  
  6.      super();  
  7.   }  
  8.     
  9.    render() {  
  10.       
  11.       return (  
  12.         <div>  
  13.         <h2>This is header</h2>  
  14.         <h3> Employee: {this.props.empdetails.name}</h3>  
  15.         <h3> Project Name: {this.props.empdetails.project}</h3>  
  16.         <h3> Time Duration: {this.props.empdetails.duration}</h3>  
  17.         <ul>  
  18.             {this.props.skills.map((skill,i)=><li key={i}>{skill}</li>)}  
  19.         </ul>  
  20.          </div>  
  21.       );  
  22.    }  
  23. }  
  24.   
  25. Header.defaultProps ={  
  26. skills:["C#","MVC","Angular","Nodejs"]  
  27. }  
  28. export default Header;   

The following will be our output.

React
PropTypes

Using propTypes in a component, we can define the validation for the properties of a component. That means we can define the datatype or required filed for the properties. Let’s take an example.

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.       
  8.   }  
  9.     render() {  
  10.      var name="Pankaj";  
  11.      var age=23;  
  12.      var city="Alwar"  
  13.           return (  
  14.           <div>  
  15.            <h3>This is main Component</h3>  
  16.            <Header name={name} age={age} city={city}></Header>  
  17.          </div>  
  18.       );  
  19.    }  
  20. }  
  21.   
  22. export default Main;   

Header.jsx 

  1. import React from 'react';  
  2.   
  3. class Header extends React.Component {  
  4.     
  5.   constructor(){  
  6.      super();  
  7.   }  
  8.     
  9.    render() {  
  10.       
  11.       return (  
  12.         <div>  
  13.         <h2>This is header</h2>  
  14.         <h3>{this.props.name}</h3>  
  15.         <h3>{this.props.age}</h3>  
  16.          <h3>{this.props.city}</h3>  
  17.          </div>  
  18.       );  
  19.    }  
  20. }  
  21.   
  22.   
  23. export default Header;   

When you save all of the above changes, you will get the following result.

React
Now, go to the “main.jsx” file and make any changes into “age” variable.

React
In the above screen, we can see that we changed the “age” variable from string to array type. So, the following will be the output.

React
In “Header” component, we don’t define any datatype and another validation for the properties, so we can pass any value to properties; but in a component, we can define the datatypes for properties. Now, 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.   }  
  8.     
  9.    render() {  
  10.       
  11.       return (  
  12.         <div>  
  13.         <h2>This is header</h2>  
  14.         <h3>{this.props.name}</h3>  
  15.         <h3>{this.props.age}</h3>  
  16.          <h3>{this.props.city}</h3>  
  17.          </div>  
  18.       );  
  19.    }  
  20. }  
  21.   
  22. Header.propTypes = {  
  23.    name: React.PropTypes.string.isRequired,  
  24.    age: React.PropTypes.number,  
  25.    city: React.PropTypes.string.isRequired  
  26. }  
  27. export default Header;   

When you save the above changes, you will get the same result as previous.

React
But this time, you get some warning in console of the browser.

React
This warning says that “Header” requires the “age” property of number type but we are passing the “Age” property of “array” type. So, change the datatype of “age” variable from array to number in “Main” component and this warning will resolve.

React
Output

React
State

State is used to store the data into component. In other words, State is the place from where we get the data into our component. We always try to make the state-less component, because each component will render several lifecycle hooks that can affect the performance of component. So try to make a parent component and define all the states for that component.

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.           name:"Pankaj",  
  9.           age:23,  
  10.           city:"Alwar"  
  11.     }  
  12.   }  
  13.     render() {  
  14.       
  15.           return (  
  16.           <div>  
  17.            <h3>This is main Component</h3>  
  18.           <h3>{this.state.name}</h3>  
  19.         <h3>{this.state.age}</h3>  
  20.          <h3>{this.state.city}</h3>  
  21.          </div>  
  22.       );  
  23.    }  
  24. }  
  25.   
  26. export default Main;   

Output

React
Above is a simple example of state in React, but why do we need state in React? Let’s take an example and understand the role of state into a React component. Replace the code of Main.jsx file with 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.      console.log('constructor executed')    
  8.   
  9.     this.state={  
  10.           name:"Pankaj",  
  11.           age:23,  
  12.           city:"Alwar"  
  13.     }  
  14.     this.number=1200;  
  15.   }  
  16.   componentWillMount() {    
  17.       console.log('componentWillMount executed')    
  18.    }    
  19.     
  20.    componentDidMount() {    
  21.       console.log('componentDidMount executed')    
  22.    }    
  23.     
  24.    componentWillReceiveProps(newProps) {        
  25.       console.log('componentWillReceiveProps executed')    
  26.    }    
  27.     
  28.    shouldComponentUpdate(newProps, newState) {    
  29.     console.log('shouldComponentUpdate executed')    
  30.       return true;    
  31.    }    
  32.     
  33.    componentWillUpdate(nextProps, nextState) {    
  34.       console.log('componentWillUpdate executed');    
  35.    }    
  36.     
  37.    componentDidUpdate(prevProps, prevState) {    
  38.       console.log('componentDidUpdate executed')    
  39.    }    
  40.     
  41.    componentWillUnmount() {    
  42.       console.log('componentWillUnmount executed')    
  43.    }  
  44.    changeData(){  
  45.      this.number=1823;  
  46.      console.log(this.number);  
  47.    }    
  48.   
  49.     render() {  
  50.       
  51.           return (  
  52.           <div>  
  53.            <h3>This is main Component</h3>  
  54.           <h3>{this.state.name}</h3>  
  55.         <h3>{this.state.age}</h3>  
  56.          <h3>{this.state.city}</h3>  
  57.          <h3>{this.number}</h3>  
  58.           <input type="button" onClick={()=>this.changeData()} value="change State"/>  
  59.          </div>  
  60.       );  
  61.    }  
  62. }  
  63.   
  64. export default Main;   

Output

React
Now, click on the “Change State” button; you will get the following output.

React
You can see that the value of number has been changed from 1200 to 1823 but View is not updated. Let’s make some changes into code and examine the result. Replace the below line of code into “chnageData” method.

this.setState({name: "Pankaj Choudhary"})

React

After making the above change, now click on the “Change State” button. This time, we will get the following output.

React
You can see that this time, View has been updated. So whenever state of the component is changed, it re-renders the component also. Here, a point to notice is that React doesn’t re-render the whole component, instead it only re-renders the updated section.

Here, I am using the “Google Chrome” browser. If you are using Chrome too, then go to the “Developer Tools” and enable the “Paint Flashing” option.

React

After enabling this feature, when any section of the screen will update, it will highlight the updated section. Now, click on the “Change State” button again and check the result.

React

You can see that only “Name” and “Number” section is updated because we changed these values only. So React only reflects the updated section instead of whole component, that makes it faster.

State-less Component:

In React, we can create State-less components. Let’s take an example of how to create it.

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.           name:"Pankaj",  
  9.           age:23,  
  10.           city:"Alwar"  
  11.     }  
  12.     this.number=1200;  
  13.   }  
  14.    changeData(){  
  15.      this.number=1823;  
  16.      console.log(this.number);  
  17.      this.setState({name: "Pankaj Choudhary"})  
  18.    }    
  19.   
  20.     render() {  
  21.       
  22.           return (  
  23.           <div>  
  24.            <h3>This is main Component</h3>  
  25.           <h3>{this.state.name}</h3>  
  26.         <h3>{this.state.age}</h3>  
  27.          <h3>{this.state.city}</h3>  
  28.          <h3>{this.number}</h3>  
  29.          <Header data="Header Component"></Header>  
  30.           <input type="button" onClick={()=>this.changeData()} value="change State"/>  
  31.          </div>  
  32.       );  
  33.    }  
  34. }  
  35.   
  36. export default Main;   

Header.Jsx 

  1. import React from 'react';  
  2.   
  3. class Header extends React.Component {  
  4.     
  5.   constructor(){  
  6.      super();  
  7.   }  
  8.     
  9.    render() {  
  10.       
  11.       return (  
  12.         <div>  
  13.          <h3>{this.props.data}</h3>  
  14.          </div>  
  15.       );  
  16.    }  
  17. }  
  18.   
  19. Header.propTypes = {  
  20.    data: React.PropTypes.string.isRequired  
  21. }  
  22. export default Header;   

Output

React

In “Header” component, we didn’t use the State; we only used Properties so we can change the “Header” component into a stateless component. If you want to make a component stateless, just make it a const function like below.

Header.jsx 

  1. import React from 'react';  
  2.   
  3. const Header  =(props)=> {    
  4.   return (  
  5.         <div>  
  6.          <h3>{props.data}</h3>  
  7.          </div>  
  8.       );  
  9. }  
  10.   
  11. Header.propTypes = {  
  12.    data: React.PropTypes.string.isRequired  
  13. }  
  14. export default Header;   

In the above code, we removed the “React.Component” class and converted the “Header” class to const function. Also, we removed the render function and write the return function only. So after making all the above changes, now our “Header” component is a stateless component.

Conclusion

In this article, we learned about React properties and State. In our next article, we will learn about Routing. 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