Reactjs State With Update Onclick Example

React.js

Nicesnippets

3842

21-01-2020


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;

I hope it can help you...


Recommended Posts