State is similar to props, but it is private and fully controlled by the component. We can create state only in class components. It is possible to update the state/Modify the state. In this article, we will discuss about State in React Component. I will show you two way to initialize state in React Component:-
1. Directly inside class
In Directly inside class, we can write a class component without a constructor. If we write state without constructor then it will work as property. Let me explain through an example:-
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import React from "react"; import ReactDOM from "react-dom"; class Employee extends Component{ //States -- Here it is a class property state ={ name: "Pradeep", empId: this.props.empId } render(){ return ( <h1> Your Name: {this.state.name}</h1> <h1> Your Name: {this.state.empId}</h1> ) } } ReactDOM.render(<Employee/>,document.getElementById("root")); |
In the above example, I declare an Employee class component with State. Here State is a class property. You can see, I am getting state value using this.state which is the correct way to access class property details.
Note:-
- The state property is referred as state.
- This is a class instance property
Inside the Constructor
When the component class is created, the constructor is the first method called, so it’s the right place to add a state. When we create a constructor, It is required to call the parent class constructor. To call parent class constructor you need to define super(props) function or method. When you call super with props. React will make props available across the component through this.props. The class instance has already been created in memory, so you can use “this” to set properties on it.
Example:
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import React from "react"; import ReactDOM from "react-dom"; class Employee extends Component{ constructor(props){ super(props); this.state ={ name: "Pradeep", empId: this.props.empId }; } render(){ return ( <h1> Your Name: {this.state.name}</h1> <h1> Your Name: {this.state.empId}</h1> ) } } ReactDOM.render(<Employee/>,document.getElementById("root")); |
In the above example, I created a class component with a constructor. To call parent class constructor you can see, super(props) function or method is defined.
Pradeep Maurya is the Professional Web Developer & Designer and the Founder of “Tutorials website”. He lives in Delhi and loves to be a self-dependent person. As an owner, he is trying his best to improve this platform day by day. His passion, dedication and quick decision making ability to stand apart from others. He’s an avid blogger and writes on the publications like Dzone, e27.co