1

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?

Submitted December 31st 2020 by Admin

Answers
0

class App extends Component { constructor() { super(); this.state = { todos: ToDoData, }; this.handleChange = this.handleChange.bind(this); } handleChange(id) { console.log("changed", id); } render() { const _this = this; const ToDoItems = this.state.todos.map(function (content) { return ( <ToDoItem key={content.id} content={content} handleChange={_this.handleChange} /> ); }); return <div>{ToDoItems}</div>; }
}

You need to add this.handleChange = this.handleChange.bind(this) and save this into _this variable because could not access this in callback.

Admin | 9 months ago


0

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

Admin | 9 months ago



Relevant Questions