1

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.

3 Answers 3

1

If you are using babel and don't want to mutate your state directly (about mutating state, see my previous answer here), the easiest way is to use the computed property names - wrap the property name in brackets like [variable]:

const n = Math.floor((Math.random() * 3) + 1)
this.setState({
  ['valvar' + n]: 'hello'
})

You can see the example here: http://codepen.io/CodinCat/pen/YNjJBb?editors=0011

Sign up to request clarification or add additional context in comments.

Comments

1

Directly changing state is bad.

What you can do in this case is create a object and call setState with it.

var modifyState = {};
modifyState[createVar] = "HELLO";

this.setState(modifyState);

Or even better and cleaner with ES6 enhanced object literal

this.setState({
  [createVar]: 'HELLO'
});

Comments

0

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"
})

2 Comments

Yes that I know,for example if math.random produces "1" local variable craeteVar will be "valvar1" that is defined in initial state
Try this this.state[createVar] ==""

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.