Cecilia Chan
Cecilia Chan

Reputation: 739

setState unexpected token using e.target.name

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>
)
}

Upvotes: 0

Views: 3009

Answers (1)

Govind Rai
Govind Rai

Reputation: 15848

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.

Upvotes: 5

Related Questions