0

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.

1
  • Could you post full code of yout components? Commented Nov 19, 2017 at 21:18

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.