☰ See All Chapters |
Component State in ReactJS
The state is a built-in React object that is used to contain data or information that belongs to the component. When this state object changes, React re-renders the component to the browser. The change in state can happen as a response to user action or system-generated events and these changes determine the behavior of the component and how it will render.
Creating the state Object
The state object is initialized in the constructor. The state object can store multiple properties.
import React from 'react';
class EmployeeComponent extends React.Component { constructor(props) { super(props); this.state = { name: "Manu Manjunatha", gender: "Male", salary: "100", age: 20 }; } render() { return <h1>I am Employee</h1>; } } export default EmployeeComponent; |
Using the state Object
We can reference the state object by using syntax: this.state.propertyname
import React from 'react'; class EmployeeComponent extends React.Component { constructor(props) { super(props); this.state = { name: "Manu Manjunatha", gender: "Male", salary: "100", age: 20 }; } render() { return ( <div> <h1>I am Employee</h1> <p> Name: {this.state.name} Gender: {this.state.gender} Salary {this.state.salary} Age: {this.state.age} </p> </div> ); } } export default EmployeeComponent; |
Changing the state Object
this.setState() is used to change the value of the state object. setState() function performs a shallow merge between the new and the previous state. When any value in the state object changes, the component will re-render, meaning that the output will change according to the new value(s).
employee.component.js
import React from 'react';
class EmployeeComponent extends React.Component { constructor(props) { super(props); this.state = { name: "Manu Manjunatha", gender: "Male", salary: "100", age: 20 }; } changeAge = () => { this.setState({age: document.getElementById("newAge").value}); } render() { return ( <div> <h1>I am Employee</h1> <p> Name: {this.state.name} <br></br> Gender: {this.state.gender} <br></br> Salary {this.state.salary} <br></br> Age: {this.state.age} <br></br> </p> <input type = "text" id ="newAge"></input> <button type="button" onClick={this.changeAge} >Change Age</button> </div> ); } }
export default EmployeeComponent; |
index.js
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import EmployeeComponent from './components/employee.component'; import reportWebVitals from './reportWebVitals';
ReactDOM.render( <React.StrictMode> <EmployeeComponent></EmployeeComponent> </React.StrictMode>, document.getElementById('root') );
reportWebVitals(); |
All Chapters