So say you have a child component that returns a number of input fields and takes a data object as a prop.
class InputFields extends React.Component {
render() {
let data = this.props.data
return (
<div className='input-group'>
<input type='text' defaultValue={data.name} onChange={this.props.update} />
<input type='text' defaultValue={data.age} onChange={this.props.update} />
<input type='text' defaultValue={data.email} onChange={this.props.update}/>
</div>
)
}
}
And the parent component might look something like:
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
items: getItemsFromSomewhere()
}
}
update(event) {
/* Somehow update main state here? */
}
render() {
/* imagine this as an array of objects, each with name, age, email ,etc. */
var items = this.state.items.map(item => {
return <InputFields data={item} update={this.update.bind(this)} />
})
return <div className='itemLists'> {items} </div>
}
}
Within this.props.update
I want to set the corresponding state for the data
object which was passed down. But the onChange
function only receives the synthetic event which only provides a reference to the DOM element itself.
Whats the best way to find which state field needs to be updated, e.g., when the input field for data.name
is changed, how can I propagate that up to the state within the main parent?
I know that refs
could be used, but how can I know which ref
to grab on the change event? Do I just have to iterate through all of them?