samedi 23 mars 2019

React design question about creating remove functionality

This is a little long winded.

I would like advice on how to go about making the functionality of a remove button. I am relatively new to react and should have planned this project before I embarked. Either way I am here now and looking for some advice before I tackle the remove functionality tomorrow.

In this component I create a method called "displayFood" in which I take an array from props that has in it string values of the names of foods that the user wanted to add to the refrigerator. For example: [yogurt, milk, egg, yogurt, yogurt]. I then create an object that maps this array to key value pairs based on name and quantity, for example: {"yogurt": 3, "milk": 1, "egg": 1}. After this I create an array that holds what I want to render to the user which is each item that they put in the fridge and the quantity of that item. I also have a remove button. I have been thinking about how to remove Items but do not know how to go about doing so.

If, for example the user deletes yogurt I want the value to decrease by one, and if the user deletes a item with quantity 1 then it should go away.

This is a pretty specific question thank you for your time.

import React from 'react';
import "./style.scss";

function InFrige(props) {

  const handleRemove = (e, counts) => {
    console.log(e.target.name)
  }

  const displayFood = () => {
     var counts = {};
    props.foodAddedByUser.forEach(function(x) { counts[x] = (counts[x] || 0) + 1; });

    let foodItems = []
    for(var index in Object.entries(counts)){
        foodItems.push(
           <div className="inFrige-food-item" key={index}>
            <h3>{Object.keys(counts)[index]} x{Object.values(counts)[index]}</h3>
             <button onClick={handleRemove} name={Object.keys(counts)[index]}>Remove</button>
           </div>
         )
    }
  return foodItems
  }

  return (
    <div>
      <div className="inFrige-food-container">
          {displayFood()}
      </div>
    </div>
  )
 }

 export default InFrige;

Aucun commentaire:

Enregistrer un commentaire