State in ReactJS

React State
The state is an updatable structure. In a component, change in state over time can happen. The state is used to contain data or information about the component and also take the responsibility to make a component dynamic and interactive. The components that have their own state are known as a stateful component, while the components that don’t have their own state are known as a stateless component.

Methods:
setState() method: It is used to set a state and it also triggers UI updates on calling.
getInitialState(): It is used to set an initial state before any interaction occurs.

Defining State Example:

import React, { Component } from 'react';  
class App extends React.Component {  
constructor() {  
super();  
this.state = {  
data:   
[  {             
"name":"Dhoni"             
},  
{            
"name":"Kohli"             
},  
{    
"name":"Pandya"          
}  ]  
}  
}  
render() {  
return (  
    {this.state.data.map((item) => )}
); } } class PLAYERname extends React.Component { render() { return (

Player Names

); } } class List extends React.Component { render() { return (
  • {this.props.data.name}
); } } export default App;

Output:

Player Names
     ●	Dhoni
     ●	Kohli
     ●	Pandya

Explanation:
To declare a default set of values a class constructor is used. It assigns an initial state using this.state. The render() method renders the ‘this.state’ property. Here we are creating a stateful component using ES6 syntax. The super() method initializes this.state.

Changing the State:
We can also change the component state. For this, we are using the setState() method. We then pass a new state object as the argument.

Example:

import React, { Component } from 'react';  
class App extends React.Component {   
constructor() {  
super();        
this.state = { displayBio: false };  
console.log('Component this', this);  
this.toggleDisplayBio = this.toggleDisplayBio.bind(this);  
}  
toggleDisplayBio(){  
this.setState({displayBio: !this.state.displayBio});  
}  
render() {  
return (  

Hello World

{ this.state.displayBio ? (

Have a Great Day.

) : (
)}
) } } export default App;

Output 1: