shubham agrawal shubham agrawal - 1 year ago 70
React JSX Question

How to mutate state using variable in Reactjs

I am new to

Reactjs
and got stuck while experimenting in my code.I am using
math.random
to find values between
0-9
and concatenating with
valvar
to get multiple variables.I want to find the state of corresponding variable.

Here is my code.

getInitialState: function(){
return{valvar2:"",valvar3:"",valvar4:"",valvar5:"",valvar6:"",valvar7:"",valvar8:"",valvar9:""}
},
handleClick: function(){
var createVar="";
createVar ="valvar"+Math.floor((Math.random() * 9) + 1);
if(this.state.createVar==""){
this.setState({createVar:"HELLO"})
}


But this code is not working, I am not sure why.This is just an example not my original code.

Answer Source

You don't have createVar defined in your state, it's just local variable in handleClick. So this condition: this.state.createVar=="" is never met because it's undefined. You have to define createVar in your initial state.

If you want to use produced value as state object property name use this:

 handleClick: function(){
    var createVar="";
    createVar ="valvar"+Math.floor((Math.random() * 9) + 1);
    if(this.state[createVar] == ""){
        let newState = {};
        newState[createVar] = "HELLO"
        this.setState(newState)
    }
}

or if you use ES2015:

this.setState({
   [createVar]: "HELLO"
})
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download