What is a state in React JS with an example
In this chapter, you will learn about What is a state in React JS with an example. As we know every class will be having a property that holds the property value. In the same manner, when you extend the react Component class, the class gets the state object instance. The below list of points helps you understand what is the state.
What is State in React JS?
- A state is an inbuilt object, means it is a reserved key in the React JS.
- The state holds the property value with the keys that belong to the components
- The state is mutable and can be changed by the setState method
- If the state is been changed it lead react to re-render DOM
- The state is managed from inside a Component.
- The state property is only available in Components that extend it
- In the version, 16.8 new feature hooks have been introduced to manage state in functional Component
How to change the state in React JS?
- You can use the setState() method to update state property
- The setState() method ensure that React gets to know about the update in state property
- Then the React updates the DOM.
Now we will see the example for creating the state and updating the state
Step 1:
Create the file src/Employee/Employee.js if you have it already paste the below code snippet
import React from 'react'; const employee = (props) => { return ( <div> <p>Hi I am {props.name} and my employee ID: {props.empId}, email: {props.email}</p> <p> {props.children}</p> </div> ) } export default employee;
Steps 2:
Create the file src/App.js if you have it already paste the below code snippet
import React, {Component} from 'react'; import './App.css'; import Employee from './Employee/Employee' class App extends Component { state = { employee : [ {name: 'Stark', empId:'123'}, {name: 'Mickel', empId:'124'}, {name: 'John', empId:'125'} ] } addEmployeeEmail = () => { this.setState({ employee : [ {name: 'Stark', email:'123', email:'stark@react.com'}, {name: 'Mickel', empId:'124', email:'mickel@react.com'}, {name: 'John', empId:'125', email:'john@react.com'} ] }) } render() { return ( <div className="App"> <h1>Welcome to react JS tutorial</h1> <button onClick = {this.addEmployeeEmail}>Update employee emails</button> <Employee name={this.state.employee[0].name} empId={this.state.employee[0].empId} email={this.state.employee[0].email} /> <Employee name={this.state.employee[1].name} empId={this.state.employee[1].empId} email={this.state.employee[1].email} /> <Employee name={this.state.employee[2].name} empId={this.state.employee[2].empId} email={this.state.employee[2].email} /> </div> ); } } export default App;
Now you should see the output
If you click on the button Update employee emails, you should be able to see the below output
One thought on “What is state in React JS with an example”
Comments are closed.