Search code examples
reactjsdestructuring

argument automatically generated on onChange event handler


I found the handleChange "Event Handler" code below on StackOverflow and used it. Everything works fine. Regarding this handleChange "Event Handler", my questions are:

  1. How does {target} become an argument of handleChange? Is it default behavior of onChange to send the target to the event handler?

  2. Why is it necessary to use {target}? Why can't one simply use target? Is this an example of the destructuring feature in ES6?

Note to self: the square brackets [] around the property name target.name are a new feature in ES6, called computed property names


Constructor

this.state = {
  username: "",
};

Render

username: <input type="text" name="username" value={ this.state.username} onChange={ this.handleChange } />

Event Handler

handleChange = ({ target }) => {
  this.setState({
    [target.name]: target.value
  });
}

Solution

    1. target is a property on the event object. By setting your onClick handler like this, onChange={ this.handleChange } you are automatically passing the event object as an argument to the handleChange-method.

    It is shorthand for writing onChange={ event => this.handleChange(event) }

    1. Yes, that is an example of the destructuring feature. You are destructuring the event argument to extract the target property.
    handleChange = ({ target }) => {
      this.setState({
        [target.name]: target.value
      });
    }
    
    // could also be written as
    
    handleChange = (event) => {
      this.setState({
        [event.target.name]: event.target.value
      });
    }
    
    // or
    
    handleChange = (event) => {
      const { target } = event;
      this.setState({
        [target.name]: target.value
      });
    }