JakAttk123
JakAttk123

Reputation: 1806

Deleting a list item when it's clicked in React

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?

Upvotes: 1

Views: 557

Answers (1)

RIYAJ KHAN
RIYAJ KHAN

Reputation: 15292

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

Upvotes: 1

Related Questions