Changing state dynamically in reactJs

Chaging state :

Idea of state change  in reactjs component :
In react the state is always an object. In state the property maps to key : value pair. These values can be any values in the javascript. It may be string , number or an other object.

constructor(props){

super(props);

this.state = {deadline : ‘December 25, 2017’};

}

Now, we want to change the state dynamically. For this we need to take the advantage special method in react Js. It is called setState().

changeDeadline(){

this.setState({..});

}

Note : We can never mutate or change the state directly.

For example :

this.state.deadline = ‘November 20,2017’; //This is the wrong way

The reactjs will never render it. This will never work , instead we need to use the setter method.

So here is the right solution :

changeDeadline(){

this.setState({deadline : ‘November 20,2017’})

}

If we want to call it from button click , then it will be :

<button onClick={()=>this.changeDeadline()}>Calculate</button>

Here we are using the ESMA6  anonymous  function to prevent the script to get crashed.

this.changeDeadline() : Here this is a keyword refers to current object reference.

Changing the data from the input field :

No again I have taken the new key-value pair with key as city and value as empty for. Because we want to change the key-value pair from the textfield dynamically.

constructor(props){

super(props);

this.state = {

city : ‘’

}

}

<input onChange={event=>console.log(event.target.value)}>

In the onChange function we are adding an event

Also on the change activity for the textfield we are actually trying to log (print) the event.

It changes everytime the user changes the textfield.

In the same way , if you want to change the state dynamically from the textfield, then we have to use

<input onChange={event=>setState({city : event.target.value})}/>

By Pankaj Kumar Agarwal

 

Leave a reply:

Site Footer