React JS Tutorial - Changing State

In this tutorial, we will learn about changing state in React. Let's see how to update the state in our application.

Go to your project and open the Post Component. Inside the Post Component, let's create a button and add an onClick event to it.


<button onClick={} >Change State</button>

Next, we need to create a function that will handle the state change.


handleChangeState=(e)=>{
this.setState({
name:'John',
age:28
});
}

Now, add this function to the onClick event.


<button onClick={this.handleChangeState} >Change State</button>

Let's check the result. Switch to your browser and navigate to localhost:3000. You should see the button.

Click on the button, and you will see that the state has been updated. Notice the changes to the name and age.

Updating the State's Skill Property

Now, let's update the state's skill property. Switch to your project and inside the handleChangeState function, add the following code:


handleChangeState=(e)=>{
this.setState({
name:'John',
age:28,
skills:['php','java','nodejs']
});
}

Save the file and let's check the result again. Switch to your browser and click on the button.

You should see that the skills have been updated. This demonstrates how to change the state in React.

By following these steps, you can update the state in your React application and see the changes reflected in the UI.