Today now in this blog i will show about reactjs state. We know in reactjs state means it is an internal object of class and also it’s a private. So we can not use it out of class. So this is one type of object but we know it’s work as like a variable. So in this variable we have a key and also a value and we can update. But props we can not change.
State Example With Onclick Button Count
So now we need to use state first we have to define a constructor and need to call “super();” keyword. Now this is not a react keyword but it’s a javascript super keyword.So we need to update state we 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;
Read Also : How To Create Functional Component In React JS ?
hope it will help you. Also you can follow us on Facebook