Search code examples
reactjsreact-props

Unable to pass function to a child component in ReactJS


I have 2 files.

App.js

class App extends Component {
  constructor() {
    super();
    this.state = {
      todos: ToDoData,
    };
  }

  handleChange(id) {
    console.log("changed", id);
  }

  render() {
    const ToDoItems = this.state.todos.map(function (content) {
      return (
        <ToDoItem
          key={content.id}
          content={content}
          handleChange={this.handleChange}
        />
      );
    });

    return <div>{ToDoItems}</div>;
  }
}

And ToDoitem.js

function ToDoItem(props) {
  console.log(props);
  return (
    <label className="container">
      <input
        type="checkbox"
        checked={props.content.is_complete}
        onChange={() => props.handleChange(props.content.id)}
      />
      {props.content.title}
      <br />
    </label>
  );
}

It says

TypeError: Cannot read property 'handleChange' of undefined

  20 |     <ToDoItem
  21 |       key={content.id}
  22 |       content={content}
> 23 |       handleChange={this.handleChange}
     | ^  24 |     />
  25 |   );
  26 | });

I am following a tutorial and exactly this same code works for them but not for me. Where am I doing wrong?


Solution

  • This appears to be a scoping issue - the classic JS "this" dilemma.

    Try swap:

    const ToDoItems = this.state.todos.map(function (content) {

    to

    const ToDoItems = this.state.todos.map((content) => {

    This approach will keep "this" in scope