0

My onChange handler got unexpcted token, I would like to use e.target.name which I expect is keyword, what's wrong?

onChange = e => {
    this.setState({
        e.target.name: e.target.value //error here
    })
  }

  render() {
    return (
      <section>
        <input type="text" name="keyword" value={this.state.keyword} onChange={() => this.onChange} />
</section>
)
}
Cecilia Chan
  • 679
  • 2
  • 8
  • 17
  • Basically a duplicate of [Using a variable for a key in a JavaScript object literal](https://stackoverflow.com/questions/2274242/using-a-variable-for-a-key-in-a-javascript-object-literal). – Felix Kling Sep 07 '17 at 03:03

1 Answers1

5

If you want to use computed property names, here's the syntax:

onChange = e => {
    this.setState({
        [e.target.name]: e.target.value
    })
  }

  render() {
    return (
      <section>
        <input type="text" name="keyword" value={this.state.keyword} onChange={this.onChange} />
</section>
)
}

Also you don't need to pass your onChange function inside an anonymous function. Simply reference it by passing it to the onChange prop.

Govind Rai
  • 14,406
  • 9
  • 72
  • 83