Reputation: 291
I am trying to change the input value on dynamically added input fields.
Each input field value is set to a state value which is made of an array.
Seems like there should be a simple solution for this.. But I can't just figure it out.
JSfiddle: https://jsfiddle.net/o51Lkvm6/1/
handleInputChange = (e) => {
this.setState({
[e.target.name]: e.target.value
});
}
render() {
return (
<div>
{ this.state.data.map((d, index) =>
<input name={d.Name} type="text" className="form-control"
value={d.Name} onChange={this.handleInputChange} />
)}
</div>
);
}
Update: Is it possible to solve this without having to use defaultvalue? Since React does not recommend "Uncontrolled Components"?
Upvotes: 0
Views: 3646
Reputation: 1035
First of all there are couple issues with your code:
this.handleInputChange = this.handleInputChange.bind(this)
or modify your existing function to:
handleInputChange = e => {};
value={this.state.data[index]["Name"]}
<input
key={d.ID}
data-index={index}
name={d.Name}
type="text"
className="form-control"
value={this.state.data[index]["Name"]}
onChange={this.handleInputChange}
/>
handleInputChange = e => {
const stateDataCopy = this.state.data.slice();
const objectCopy = Object.assign({}, stateDataCopy[e.target.dataset.index]);
objectCopy["Name"] = e.target.value;
stateDataCopy[e.target.dataset.index] = objectCopy;
this.setState({ data: stateDataCopy });
};
Upvotes: 1
Reputation: 7682
ok I fixed it for you
do these 2 things
handleInputChange(e){
make this an arrow function so it has the concept of this
like so: handleInputChange = (e) => {
and use defaultValue
instead of value
in the input
updated fiddle for you: https://jsfiddle.net/a17gywvp/1/
Upvotes: 1