Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - this.input.value vs handle change

Tags:

reactjs

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.
like image 639
Nick Avatar asked Oct 04 '17 19:10

Nick


People also ask

How do you handle input change in React?

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.

Why we use handleChange in react JS?

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.

How do you get value of inputs onChange when they are inside map functions?

map((item, index) => ( <div> {item.name} <input key={index} value={this. state. objects[index]} onChange={this. handleChange.


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>
    )
}
like image 112
Chase DeAnda Avatar answered Sep 24 '22 02:09

Chase DeAnda