I have this ponent:
...
onInputChange = evt => {
const target = evt.target;
let value = null;
if (target.nodeName === "INPUT")
value = target.value; //works well
else if (target.nodeName === "SPAN")
value = target.innerText; //works well
const name = target.name; //works well if it's the input, doesn't if it's the span
this.setState({[name]: value});
}
render() {
...
<input name="myFirstValue" onChange={onInputChange} />
<span name="mySecondValue" contentEditable="true" onInput={onInputChange}></span>
...
}
...
When it's the input
that triggers the event, it works well. But the problem is when it's the span
: target.name
returns undefined
and not 'mySecondValue'
.
Is this a bug from React? If so, is there a workaround?
Thank you for your help.
I have this ponent:
...
onInputChange = evt => {
const target = evt.target;
let value = null;
if (target.nodeName === "INPUT")
value = target.value; //works well
else if (target.nodeName === "SPAN")
value = target.innerText; //works well
const name = target.name; //works well if it's the input, doesn't if it's the span
this.setState({[name]: value});
}
render() {
...
<input name="myFirstValue" onChange={onInputChange} />
<span name="mySecondValue" contentEditable="true" onInput={onInputChange}></span>
...
}
...
When it's the input
that triggers the event, it works well. But the problem is when it's the span
: target.name
returns undefined
and not 'mySecondValue'
.
Is this a bug from React? If so, is there a workaround?
Thank you for your help.
Share Improve this question asked Feb 18, 2019 at 3:30 JacopoStanchiJacopoStanchi 2,1465 gold badges40 silver badges70 bronze badges2 Answers
Reset to default 6You can put a "name" attribute on any element you want, but only <form>
"interactive" elements have DOM APIs that allow you to treat it as a gettable/settable property on the DOM node. Otherwise, you have to use .getAttribute()
and .setAttribute()
(which should work for <input>
etc too).
Thus
const name = target.getAttribute("name");
or maybe
const name = target.name || target.getAttribute("name");
event.target.name
works when the event is fired on any element that has a name attribute.
<input
type="text"
id="nume"
**name="lastName"**
class="form-control"
placeholder="Nume"
required
autoFocus
defaultValue={employeeData.lastName || ""}
onChange={handleChange}
/>