I have an object in state ("car") with multiple keys, one of which is an array ("features"). There's a couple things I'm trying to do with it.
- I want to push another string (another feature) onto the "features" array every time I click the "Add Feature" button.
- I want to be able to update the state of each string/feature in the "features" array when I type in the respective input.
I've researched this online quite a bit and haven't found anything (maybe because this isn't possible). Either way, here's my code:
class Car extends React.Component {
state = {
car: {make: 'Toyota', model: 'Camry', features: []},
}
handleChange = (e, index) => {
const value = e.target.value
let features = this.state.car.features.slice() // create mutable copy of array
features = features[index].concat(value)
this.setState({...this.state.car, features: features})
}
handleAddFeature = () => {
let features = this.state.car.features.slice()
features.push('')
this.setState({...this.state.car, features: features})
}
render() {
return (
{
this.state.car.features.map((f, index) => { return <input key={index} onChange={e => this.handleChange(e, index)}>{feature}</input>
}
<button onClick={this.handleAddFeature}>Add Feature</button>
)
}
}