Reactjs State With Update Onclick Example
Hi Friends,
In this blog we are learning about reactjs state. In reactjs state means it's internal object of class and it's a private. you can not use out of class. this is one type of object but it's work like variable. In this variable we have key and value and you can update. but props you can not change.
State Example With Onclick Button Count
You have to use state first you have to define constructor and call "super();" keyword. this is not react keyword but it's javascript super keyword. you have to update state you can use "setState()" method.
/src/User.js file
import React from 'react'
class User extends React.Component{
constructor(){
super();
this.state = {
counter:0
}
}
incrementState(){
this.setState({
counter:this.state.counter+1
})
}
render(){
return(
<div>
<h1>Counter : {this.state.counter}</h1>
<button onClick={()=>{this.incrementState()}} class="btn btn-primary">Click For Increment</button>
</div>
)
}
}
export default User;
/src/App.js file
import React from 'react';
import './App.css';
import User from './User';
function App() {
return (
<div className="App">
<header className="App-header">
<User />
</header>
</div>
);
}
export default App;
- How to Reactive Forms with Validation in Angular 18?
- Reactjs Props Example With Function and Class Components
- React Color Picker Example With Change Event
- How to Hide and Show Multiple Div in React ?
- React js File Upload Example With Axios
- How to Resize, Crop, Compress Images Before Uploading In ReactJS?
- How to Send Data From React to Node JS Express?
- Reactjs String Replace Example