React - this.input.value vs handle change

Viewed 13538

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.
1 Answers

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