Reputation: 71
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!
Upvotes: 5
Views: 7737
Reputation: 391
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)};
Upvotes: 17
Reputation: 39202
handleChange
should collect all of the information required to change state and call setState
a single time. vaslidationState
should not be changing state. It should just be returning the new style:
validationState(value) {
return (value.length > 4) ? "success" : (value.length > 2) ? "warning" : "error";
}
handleChange(name, e) {
const value = e.target.value;
const style = this.validationState(value);
const stateUpdates = {
[name]: value,
[`${name}Style`]: style
};
this.setState(stateUpdates);
}
Upvotes: 0