M
M
Moro Zota2018-03-23 15:56:56
JavaScript
Moro Zota, 2018-03-23 15:56:56

Why is the property name wrapped in square brackets in setState?

handleChange = type => ev =>{
        const {value} = ev.target
        if (value.length > limits.user.max) return
        this.setState({
            [type]: value
        })
    }

This method stands on the onChange event. Please explain so I can understand. Why is the type property wrapped in square brackets in setState?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-03-23
@morozota

Computed property names .

This method stands on the onChange event.

Doubtful statement. "Event" is "worth" not handleChange, but the function it returns. Apparently, it is necessary to handle events that occur in different places in a uniform way - the only differences are the names of the updated properties, for each of which a separate handler is created. Which, by the way, is not necessary at all - you can attach the type value to the element as a data attribute, and then you can use a common handler:
handleChange = ({ target: { value, dataset: { type } } }) => {
  if (value.length <= limits.user.max) {
    this.setState({
      [type]: value
    });
  }
}

<input onChange={this.handleChange} data-type="xxx">
<input onChange={this.handleChange} data-type="yyy">
<input onChange={this.handleChange} data-type="zzz">

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question