How do I edit multiple input controlled components in React?

Viewed 41388

I have a component that stores a contact object as state - {firstName: "John", lastName: "Doe", phone: "1234567890} I want to create a form to edit this object but if I want the inputs to hold the value of the original contact parameter, I need to make each input a controlled component. However, I don't know how to create a handleChange function that will adjust to each parameter because my state only holds {contact: {...}}. Below is what I currently have -

  getInitialState: function () {
    return ({contact: {}});
  },
  handleChange: function (event) {
    this.setState({contact: event.target.value });
  },
  render: function () {
    return (
        <div>
          <input type="text" onChange={this.handleChange} value={this.state.contact.firstName}/>
          <input type="text" onChange={this.handleChange} value={this.state.contact.lastName}/>
          <input type="text" onChange={this.handleChange} value={this.state.contact.lastName}/>
        </div>
      );
    }

I wish in my handleChange I can do something like

  handleChange: function (event) {
    this.setState({contact.firstName: event.target.value });
  }
9 Answers

The neatest approach

Here is an approach that I used in my simple application. This is the recommended approach in React and it is really neat and clean. It is very close to ArneHugo's answer and I thank hm too. The idea is a mix of that and react forms site. We can use name attribute of each form input to get the specific propertyName and update the state based on that. This is my code in ES6 for the above example:

class ContactEdit extends React.Component {

  handleChangeFor = (event) => {
    const name = event.target.name;
    const value = event.target.value;
    const { contact } = this.state;
    const newContact = {
      ...contact,
      [name]: value
    };
    this.setState({ contact: newContact });
  }

  render() {
    return (
      <div>
        <input type="text" name="firstName" onChange={this.handleChangeFor} />
        <input type="text" name="lastName" onChange={this.handleChangeFor}/>
        <input type="text" name="phone" onChange={this.handleChangeFor}/>
      </div>
    );
  }
}

The differences:

  • We don't need to assign state as value attribute. No value is needed
  • The onChange method does not need to have any argument inside the function call as we use name attribute instead
  • We declare name and value of each input in the begening and use them to set the state properly in the code and we use rackets for name as it is an attribute.

We have less code here and vey smart way to get any kind input from the form because the name attribute will have a unique value for each input. See a working example I have in CodPen for my experimental blog application in its early stage.

Here is generic one;

handleChange = (input) => (event) => {
    this.setState({
        ...this.state,
        [input]: event.target.value
    });
}

And use like this;

<input handleChange ={this.handleChange("phone")} value={this.state.phone}/>

<input> elements often have a property called name. We can access this name property from the event object that we receive from an event handler:

Write a generalized change handler

constructor () {
    super();
    this.state = {
      name: '',
      age: ''
    };
    this.handleChange = this.handleChange.bind(this);
  }
  handleChange (evt) {      
    this.setState({ [evt.target.name]: evt.target.value });
  }

render () {
    return (
      <form>

        <label>Name</label>
        <input type="text" name="name" onChange={this.handleChange} />

        <label>Age</label>
        <input type="text" name="age" onChange={this.handleChange} />

      </form>
    );
  }

source

updatePrevData=(event)=>{
    let eventName=event.target.name;
   this.setState({
       ...this.state,
       prev_data:{
        ...this.state.prev_data,
        [eventName]:event.target.value
       }

   })

   console.log(this.state)

}

You can do it without duplicate code and easy way

handleChange=(e)=>{
    this.setState({
        [e.target.id]:e.target.value
    })
}


<Form.Control type="text" defaultValue={this.props.allClients.name}  id="clientName"  onChange={this.handleChange}></Form.Control>
<Form.Control type="email" defaultValue={this.props.allClients.email}  id="clientEmail"  onChange={this.handleChange}></Form.Control>
handleChange(event){
    this.setState({[event.target.name]:event.target.value});
    this.setState({[event.target.name]:event.target.value});
  }
Related