Search code examples
reactjsbindingcreate-react-app

Cannot read property 'XYZ' of undefined – Binding Issue


I am just in the beginning of learning react and immediately have an issue about binding.

I always get the "Cannot read property 'onDismiss' of undefined"-Error and i have no idea how to fix this anymore. Tried multiple ways to bind 'this' correctly, but nothing works.

So here is the complete code of my App Component:

import React, { Component } from 'react';
import './App.css';

const list = [
{
title: 'React',
url: 'https://reactjs.org/',
author: 'Jordan Walke',
num_comments: 3,
points: 4,
objectID: 0,
}, 
{
title: 'Redux',
url: 'https://redux.js.org/',
author: 'Dan Abramov',
num_comments: 2,
points: 5,
objectID: 1,
},
{
title: 'Reddit',
url: 'https://reddit.com/',
author: 'Crazy Guys',
num_comments: 2000,
points: 3,
objectID: 2,
}, 
];

class App extends Component {

constructor(props) {
super(props);

this.state = {
  list: list,
  list_title: 'Links',
};

this.onDismiss = this.onDismiss.bind(this);
}

onDismiss(id) {
console.log(id)
//const isNotId = item => item.objectID !== id;
//const updateList = this.state.list.filter(isNotId);
}

render() {
return (
  <div className="App">
    <h2>{this.state.list_title}</h2>
    {this.state.list.map(function(item) {
        return (
          <div key={item.objectID}>
            <span>
              <a href={item.url}>{item.title}</a>
            </span>
            <span>
              {item.author}
            </span>
            <span>
              {item.num_comments}
            </span>
            <span>
              {item.points}
            </span>
            <span>
              <button 
                onClick={() => 
                  this.onDismiss(item.objectID)}
                  type="button"
              >
              Dismiss
              </button>
            </span>
        </div>
        );
    })}
  </div>
);
}
}

export default App;

Solution

  • Change

    <h2>{this.state.list_title}</h2>
    {this.state.list.map(function(item) { ... }}
    

    to

    <h2>{this.state.list_title}</h2>
    {this.state.list.map(item => { ... }}