Kristina Bressler
Kristina Bressler

Reputation: 1722

React trying to delete a item from a list

I'm learning React and I'm trying to delete an item from the list. I tried a couple of solutions but couldn't find anything to make it work. I would need an extra eye to see what I'm missing...

My code to call the delete function

handleDeletePrice = deletePrice => {

  this.setState(prevState => ({
    // spreads out the previous list and delete the price with a unique id(date)
    priceArr: prevState.priceArr.filter(item => item.date !== deletePrice)
  }));
};

and here's where I called the function in the hook(?) component. This displays a list of the prices with a delete button in each price box.

{this.state.priceArr.map((props) => (
              <PriceBox
                {...props}
                key={props.date}
                toggleEditing={this.toggleItemEditing}
                handleDeletePrice={this.handleDeletePrice}
                onChange={this.handleItemUpdate}
              />
            ))}

And in the Single Price Box Component, here's where I added the click to delete the price:

{this.props.handleDeletePrice && (
                  <button
                    type="button"
                    className="delete-btn"
                    onClick={() => this.props.handleDeletePrice()}
                    >
                      X
                    </button>
                    )}

To see my full code, you can check out my demo at CodeSandBox in which I loaded my github repo in to display my code. https://codesandbox.io/s/github/kikidesignnet/caissa

In this demo, you click on the Prices button and a Popup window open. It's another page in this single page application. In this window, you can see the list of the prices and an X button in each price box. I am also trying to use the date as a unique id since each price is supposed to be entered once a day. In other words, I'm trying to use the date as a unique id to delete the price box.

What am I missing?

Upvotes: 0

Views: 45

Answers (1)

J&#243;zef Podlecki
J&#243;zef Podlecki

Reputation: 11283

I don't understand business domain, but I think this approach can help

{this.state.priceArr.map((props) => (
              <PriceBox
                {...props}
                key={props.date}
                price={props.price}
                toggleEditing={this.toggleItemEditing}
                handleDeletePrice={this.handleDeletePrice}
                onChange={this.handleItemUpdate}
              />
            ))}
{this.props.handleDeletePrice && (
                  <button
                    type="button"
                    className="delete-btn"
                    onClick={() => this.props.handleDeletePrice(this.props.price)}
                    >
                      X
                    </button>
                    )}

Upvotes: 1

Related Questions