2

I want to use the same onChange handler for a series of inputs.

<input onChange={this.handleInputChange}
    type="text"
    data-input-name="name"
    value={this.state.name}/>

so I am attempting to use this html data attribute to store the input's name. When I go to pull the attribute off in JavaScript, I am unable to access it.

handleInputChange = (event) => {
    this.setState([event.target.inputName]: event.target.value})
}

I've tried a few permutations to no avail, and it seems difficult to debug since when I log the event.target I just see an html element in the JavaScript console.

Any advice on how to better debug this or where my syntax is going wrong?

Daniel Thompson
  • 2,193
  • 4
  • 23
  • 37

3 Answers3

4

I've noticed that you have missed an opening curly brace in your setState call. And that will throw a syntax error when you run it. It should be fixed like this:

handleInputChange = (event) => {
    this.setState({[event.target.inputName]: event.target.value})
}

For accessing your data attribute from the handleInputChange, you can do it like this:

handleInputChange = event => {
  this.setState({
    [event.target.getAttribute('data-input-name')]: event.target.value,
  });
};

And also, you can use the default name attributes that comes with these inputs like this:

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


// in your render fucntion
<input
  onChange={this.handleInputChange}
  type="text"
  name="name"
  value={this.state.name}
/>

This will work as the same as using data attributes. Hope this help!

Joshua
  • 3,055
  • 3
  • 22
  • 37
3

You could pass the input name as an argument instead of having it as a property, like so:

<input onChange={(e) => this.handleInputChange(e,"someValue")}
    type="text"
    value={this.state.name}/>

and then

handleInputChange = (event, name) => {
    this.setState([name]: event.target.value})
}
Jayce444
  • 8,725
  • 3
  • 27
  • 43
1

I was also able to find a somewhat dirty solution to pulling the value off of the event object.

event.target.attributes['data-input-name'].value
Daniel Thompson
  • 2,193
  • 4
  • 23
  • 37