3

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?

3 Answers 3

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!

Sign up to request clarification or add additional context in comments.

2 Comments

Oh neat, is that .getAttribute function part of the HtmlElement object type API?
Yep, it's part of the DOM APIs, according to one of the React core team members. stackoverflow.com/a/20383295/1727948
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})
}

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.