0

I am learning React.js, trying to build a todoList app. So in my component, I am creating a <li> element to display a to-do item that the user enters in the form. I also display a tiny delete button next to it. I basically want to delete this entry when the user clicks on the delete button. The function removeItem() I created in my component is the event handler for the button click. But when I call the removeItem() i keep getting an "typeEror, removeItem does not exist". I have tried moving it around, done binding of the this keyword, used an arrow function to no avail. Here's what the code looks like:

var TodoItems = React.createClass({

    removeItem: function() {
        alert("We are removing an Item");////////////
    },

    render: function() {
        var todoEntries = this.props.entries;

        function createTasks(item) {
    return <li key={item.key}>{item.text}<button onClick={() => this.removeItem()} className="deleteBtns">x</button></li> 
        }

        var listItems = todoEntries.map(createTasks);

        return (
            <ul className="theList">
            {listItems}
            </ul>
        );
    }
});

What am I missing?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • also your map function does not look right. Change to ` todoEntries.map(item => createTasks(item));` – Monica Acha Mar 20 '19 at 05:46
  • 1
    Use `todoEntries.map(createTasks, this)` or make `createTasks` an arrow function. See the duplicate (same problem, slightly different error due to strict mode). – Felix Kling Mar 20 '19 at 06:02
  • @Monica Acha, the map function is alright...the tasks are being created. My issue is with deleting tasks. – Gustav F N Mar 20 '19 at 06:06

1 Answers1

0

If you're learning react, you should probably be using the newest version along with the class or functional component syntax instead of React.createClass which is not recommended.

Something like this:

class TodoItems extends React.Component {
  removeItem = () => {
    alert("We are removing an Item");
  }

  render() {
    return (
      <ul className="theList">
        {this.props.entries.map((item) => (
          <li key={item.key}>
            {item.text}
            <button onClick={this.removeItem} className="deleteBtns">x</button>
          </li> 
        ))}
      </ul>
    );
  }
}

const entries = [
  {text: 'test', key: 1},
  {text: 'test2', key: 2},
];

ReactDOM.render(
  <TodoItems entries={entries} />,
  document.getElementById('app')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app" />
Austin Greco
  • 32,997
  • 6
  • 55
  • 59