Home > other >  How do you pass a function through a component that has a spread operator?
How do you pass a function through a component that has a spread operator?

Time:10-22

Sorry, beginner at react here. I am having some difficulty trying to pass info to a parent component via prop drill in order to set the values into a context API so I can pass the info to another component.

I have an array called foodItem that was passed down from App.js to the component below with onGetFood function. I created another intermediary testing function called getFoodItemInfo to pass onto the next component ChildFoodItem.

//FoodList.jsx

function FoodItem ({foodItem}, {onGetFood}) {

    function getFoodItemInfo (food) {
        onGetFood();
        console.log("FOOOD");
    }

    return (
         <ChildFoodItem {...foodItem} **getFood={getFoodItemInfo}**/>
    );
}

//ChildFoodItem.jsx

    function ChildFoodItem (food, {getFood}) {
        
            getFood();
        
            return (
            <p className="flex-container">
                {/* First row - Macros */}
                <p className='task flex-child'>
                    <Button onClick={(e) => getFood()} style={{font: "bold"}} variant="link">{food.description} </Button>
                </p>
            </p>
            )
        }

However, when I tried to pass getFood to the ChildFoodItem, I'm getting that the function is undefined? Is there a rule that you can't prop drill a function if you use a spread operator?

CodePudding user response:

You are trying to destructure the prop parameter, which is the first parameter that the component receives. By specifying multiple parameters (food, {getFood}), the props end up in food, and any other parameter will be undefined. The correct syntax would be:

function ChildFoodItem ({ getFood, ...food })

This would get the getFood function out of the props, and place the rest of them in the food variable.

For more details on that, see the "Rest in Object Destructuring" section on the "Destructuring assignment" documentation.

CodePudding user response:

Issue

React components receive only a single argument, the props object. With function ChildFoodItem (food, {getFood}) you are attempting to destructure getFood from an undefined argument. The props object you named food.

Solution

Given the props are passed as:

<ChildFoodItem {...foodItem} getFood={getFoodItemInfo} />

Then getFood can be explicitly destructured while the rest of the food props are spread into a variable named food (or any other valid identifier).

function ChildFoodItem ({ getFood, ...food }) {

  getFood();

  return (
    <p className="flex-container">
      {/* First row - Macros */}
      <p className='task flex-child'>
        <Button onClick={(e) => getFood()} style={{font: "bold"}} variant="link">{food.description} </Button>
      </p>
    </p>
  )
}
  • Related