I'm new to React and I'm struggling to ensure that form elements created from a mapped array remain controlled by React
I have an array of objects that is passed into a React component through props
vehicles: [
{make: 'make1', model: 'model1'},
{make: 'make2', model: 'model2'}
]
I'm then storing these in state (the purpose of the React component in question is to amend the vehicles array at its source)
componentWillReceiveProps() {
this.setState({
vehicles: this.props.vehicles
})
}
After this I'm mapping through the array to create jsx to be returned in render()
const vehicles = this.state.vehicles.map((vehicle, index) => {
return (
<div>
<FormGroup row>
<Col sm={1}></Col>
<Label for={`make-${index}`} sm={3}>Make</Label>
<Col sm={7}>
<Input type="text" name={`make-${index}`} id={`make-${index}`} data-context="vehicle" onChange={this.handleInputChange} value={vehicle.make} readOnly={!this.state.formEnabled} />
</Col>
<Col sm={1}></Col>
</FormGroup>
<FormGroup row>
<Col sm={1}></Col>
<Label for={`model-${index}`} sm={3}>Model</Label>
<Col sm={7}>
<Input type="text" name={`model-${index}`} id={`model-${index}`} data-context="vehicle" onChange={this.handleInputChange} value={vehicle.model} readOnly={!this.state.formEnabled} />
</Col>
<Col sm={1}></Col>
</FormGroup>
</div>
);
})
However, setting the values this way means that I can't change their state using the handleInputChange() function (or even enter text in the input fields in the browser).
Is there a way to keep dynamically created form elements controlled by React? Or is my approach fundamentally flawed?
handleInputChange()by calling setState inside your function