How to manipulating state on events in ReactJS

In previous post we have explain state example in reactjs  and events  handling in reactjs . Now In this post we are explained how to manipulating state  on event. Here is example how to change/update state onclick in reactjs . In App.js file we have state  users and onclick update users we will update state inside updateUsers using  this.setState() . This is very good example how to use this.setState() in reactjs. 
App.js :
import React, { Component } from ‘react’;
import ‘./App.css’;
import User from ‘./User/User’;
import Profile from ‘./Profile/Profile’;
class App extends Component {
state= {
users :[
{ name : ‘ram’ , salary :2000 },
{ name : ‘john’ , salary :3000}
]
}
updateUsers= () => {
this.setState(
{
users :[
{ name : ‘smith’ , salary :12000 },
{ name : ‘lara’ , salary :3400}
]
}
)
}
render() {
return (
<divclassName=”App”>
<h1> My react application </h1>
<p>Welcome, Users </p>
<buttononClick={this.updateUsers}>Update Users</button>
<Username={this.state.users[0].name}salary={this.state.users[0].salary}/>
<Username={this.state.users[1].name}salary={this.state.users[1].salary}/>
<Profileeducation=”MCA”job=”ceo”/>
</div>
);
}
}
export default App;
Now we will create class based component with name Profile (/Profile/Profile.js)
Profile.js
import React , { Component } from “react”
class Profile extends Component {
render(){
return<p>highest education is {this.props.education} and works as {this.props.job}</p>;
}
};
export default Profile;
Now we will create functional component user(/User/User.js)
User.js
import React from ‘react’;
const user = (props) =>{
return<p>I am {props.name} and my salary is {props.salary}</p>
};
export default user;
Now in browser localhost:3000
When you will click on update users button it will call updateUser() method and update state of component . After click you will see that this text change as below

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

84 − 83 =