Currently, I am working on updating a form with double input fields. The aim is for users to be able to click an 'add' button and update the state with their values, while ensuring that the two input fields are "connected". To better illustrate my goal, here is a graphical representation:
[input] [second input] [remove button]
[input] [second input] [remove button]
[input] [second input] [remove button] ...
Creating dynamic input fields becomes more challenging when dealing with two inputs. Although I have made progress in this direction, here is the current state of the code:
State:
stuff: {
item: [],
quantity: []
}
This snippet demonstrates how I was able to dynamically add a single input field:
// Mapping 'stuff' due to changes in data structure
return this.state.stuff.map((element, index) =>
<div key={index}>
<input type="text" value={element||''} onChange={this.handleChange.bind(this, index)} />
<input type='button' value='remove' onClick={this.removeInput.bind(this, index)}/>
</div>
)
handleChange(index, event) {
let stuff = [...this.state.stuff];
stuff[index] = event.target.value;
this.setState({ stuff });
}
add(){
this.setState(previousState => ({ stuff: [...previousState.stuff,'']}))
}
removeInput(index){
let stuff = [...this.state.stuff];
stuff.splice(index,1);
this.setState({ stuff });
}
I have been experimenting with different ideas, but I'm still puzzled by the addition of `''` in the `add()` function. Any insights or solutions that can help me achieve my intended functionality would be greatly appreciated.