What is better?
I have a form with 10 inputs.
Should I use this.input.value
or handle change and store it in state
?
handleChange(e) {
this.setState({input: e.target.value});
}
...
<input type="text" value={this.state.input} onChange={this.handleChange} />
or
onSubmit() {
const inputValue = this.input.value;
...
}
...
<input type="text" ref={(input) => {this.input = input;}} />
From the documentation:
When to Use Refs
There are a few good use cases for refs: Managing focus, text selection, or media playback. Triggering imperative animations. Integrating with third-party DOM libraries. Avoid using refs for anything that can be done declaratively.
The standard way to handle form input value changes is to handle them with React. This is a technique called controlled components. We can create controlled components with input , textarea , and select elements. They maintain their own state, and updates are based on user input.
handleChange is triggered by the input element and triggers the changing of the this. state. value property which in turn changes the value of the input field. This is important because react uses states to display information in the DOM.
map((item, index) => ( <div> {item.name} <input key={index} value={this. state. objects[index]} onChange={this. handleChange.
Setting up controlled inputs is kind of a pain, but I use this pattern to make it a little easier.
Create one onChange event handler for ALL inputs:
handleInputChange(e){
const target = e.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
Then, for your inputs, be sure to give it a name
that matches a key in your state to update.
render() {
const { firstName, lastName, email, acceptTerms } = this.state;
return (
<form>
<input name="firstName" onChange={this.handleInputChange} value={firstName} />
<input name="lastName" onChange={this.handleInputChange} value={lastName} />
<input name="email" onChange={this.handleInputChange} value={email} />
<input type="checkbox" name="acceptTerms" onChange={this.handleInputChange} checked={acceptTerms} />
</form>
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With