Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a variable as part of a `this.state` call ReactJS

I'm attempting to created a form validation using react-bootstrap, and would like to avoid making a validation function for each input.

I have this input:

<Input 
  hasFeedback 
  type="text" 
  label="Username" 
  bsStyle={this.state.UsernameStyle} 
  onChange={this.handleChange.bind(this, 'Username')} 
  value={this.state.Username} 
  bsSize="large" 
  ref="inptUser" 
  placeholder="Enter Username"
/>

Plus, I have two function to handle the validation and updating of the state:

handleChange: function(name, e) {
  var state = {};
  state[name] = e.target.value;
  this.setState(state);
  var namestyle  = name + 'Style';
  this.setState(this.validationState(namestyle, e));
},

&

validationState: function(style, event) {
  var length = event.target.value.length;

  if (length > 4) this.setState({style: 'success'});
  else if (length > 2) this.setState({style: 'warning'});

  return {style};
}

At this point if I change style to Username I can get this solution to work for that specific input as well. I could make an if statement and depending on the string I get in style I can call the appropriate setState, but is their a better way to do this?

Thanks!

like image 907
ekarni Avatar asked Jan 27 '16 20:01

ekarni


1 Answers

var yourVariable = "name";
this.state[yourVariable];

is equivelant to:

this.state.name;

if you want to use your variable in set state you can use this:

var value = "peter";
this.setState({[yourVariable]: value});

is equivelant to:

this.setState({name: value)};
like image 151
peter Avatar answered Oct 04 '22 20:10

peter