Reputation: 681
I am making a checklist using React. Here's my Parent
component:
<ul>
{this.props.data.map(item => {
return(
<div><Child {...item} onChange={(e) => this.handleChange("Hello", e)}/></div>);
})}
</ul>
which calls on Child
component that prints list elements:
<li>
<input
type="checkbox"
value={this.props.value}
onChange={event => this.props.onChange(this.props.id, this.props.value, event.target.checked)}
/>
{this.props.value}
</li>
and here's the handleChange
method:
handleChange(myString, e) {
console.log(e.target.id, e.target.value, e.target.checked, myString);
}
I want to pass a custom string of my own to handleChange
method but I am unable to do that. I have seen several posts regarding this topic but I need help correcting what I am doing wrong. The problem seems to be the way I send onChange
data from Child
component back to Parent
component. Above is what I have written so far. I get an error Cannot read property id of undefined
. I would appreciate some help regarding how to fix this.
Upvotes: 0
Views: 1297
Reputation: 1694
You are calling a function that's defined like this in props onChange
of Child
in the parent component:
(e) => this.handleChange("Hello", e)
with a call that's like this in Child
inside your onChange
clickhandler on the input
element:
onChange(this.props.id, this.props.value, event.target.checked)
that obviously won't work.
Change your input
element in Child
to this:
<input
...
onChange={this.props.onChange}
/>
to just pass the event object through.
Upvotes: 2