1

I'm trying to delete an item from a <ul> when the user clicks on it. Here is my List component right now:

class List extends Component {
    constructor(props) {
        super(props);
        this.handleClick = this.handleClick.bind(this);
    }

    handleClick(e) {
        //What goes here?
    }

    render() {
        const list = this.props.items.map((x, index) => {
            return <li key={index} onClick={this.handleClick}>{index+1}. {x}</li>
        });

        return (
            <ul className="list">
                {list}
            </ul>
        )
    }
}

The handleClick function runs when the user clicks on one of the <li> elements. How can I get the {index} of the element that called the function, and then use that to delete it from the array?

JakAttk123
  • 1,646
  • 3
  • 11
  • 19

1 Answers1

1

You can use Use an JS#arrow function with JS#function curry.

const list = this.props.items.map((x, index) => {
      return <li key={index} onClick={(index) => this.handleClick(index)}>{index + 1}. {x}</li>
    });

This will create a new function that calls handleClick with given params

handleClick: with function curry.

handleClick = (event) => { // get event
  return function (indexLI) {
    console.log(indexLI); //get index
    //your logic to delete item for LI and update state here
  }
}

handleClick will have both user defined params and event object

RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53
  • Thanks for the answer. Could you suggest a better key, as I know you are not supposed to use `{index}` but I'm not sure what else would work in this case. – JakAttk123 Mar 25 '18 at 05:08
  • yes `Index as a key is an anti-pattern`,it should have a permanent and unique property from list like hash value or primary key id from database,but should not be index from collection – RIYAJ KHAN Mar 25 '18 at 05:11
  • @JakAttk123 event you can use `uuid or shortid` npm packages – RIYAJ KHAN Mar 25 '18 at 05:20