2
votes

I have a React Component Posts:

import React, { Component } from 'react';

const list = [
  {
    title: 'React',
    url: 'https://facebook.github.io/react',
    author: 'Adam Beat',
    num_comments: 4,
    points: 3,
    objectID: 10,
  }, {
    title: 'Rails',
    url: 'https://www.rubyonrails.org',
    author: 'DHH',
    num_comments: 8,
    points: 4,
    objectID: 11,
  }
]

class Posts extends Component {

  constructor(props) {
    super(props); // call the constructor of the extended class
    this.state = { // bound state with the this object
      list: list,
    };
    this.onDismiss = this.onDismiss.bind(this);
  }

  onDismiss(id) {
    // const isNotId = item => item.objectID !== id;
    // const updatedList = this.state.list.filter(isNotId);
    const updatedList = this.state.list.filter(item => item.objectID !== id);
    this.setState({ list: updatedList });
  }

  render() {
    return (
      <div className="home-page ui container">
        {
          this.state.list.map(function(item) {
            return (
              <ul key={item.objectID}>
                <li>
                  <a href={item.url}>{item.title}</a>
                </li>
                <li>{item.author}</li>
                <li>{item.num_comments}</li>
                <li>{item.points}</li>
                <li>
                  <button
                    onClick={ () => this.onDismiss(item.objectID)}
                    type="button">
                    Dismiss
                  </button>
                </li>
              </ul>
            );
          })
        }
      </div>
    );
  }
}

export default Posts;

And I'm trying to remove an item from the list by clicking on "dismiss" button.

But actually I get an error: "Uncaught TypeError: Cannot read property 'onDismiss' of undefined"

What am I missing?

1
You don't need the property initializer syntax in the constructor because you are already using an arrow function callback which does the binding. - Murat Karagöz

1 Answers

6
votes

You are using this.state.list.map(function(item) { ... }), so your context is that of a map function. If you change it to this.state.list.map(item => { ... }) it will work. This is because arrow functions automatically binds to the parents this scope. And inside your map function there is no onDismiss function.

When you bind this in a constructor, onDismiss function will receive your components context. However, you still must pass your components function and in this case you are not doing that.