Sending a variable back up to parent component in React

I started coding my React app w/o thinking too much about how to divvy up the logic between parent and child(ren) components. But now, I think I have put myself in a bind.

I have a function running in a child component that returns a variable which I have to send to parent component in order to send back down to a sibling component.

Child component = searchPantry.jsx
Event in child component = handleCheck(ingredientName)
Variable created in child component = recipes
Sibling component = recipeResult.jsx
Parent component = readData.jsx

All code:

I read a couple of blogs on how to send data up to parent from child including [this] ( one but they are sending data from a JSX element. And I want to send it from a function.

The only solution I can think of is making the variable part of setState…? I think that’s bad coding practice? If anyone has any other ideas, please let me know. At a loss.

  1. Send a function that can update parent state down to child as a prop.
  2. Child calls that function and passes the recipe(s) as an argument.
  3. Sibling gets recipe as a prop.

That’s one way to do it.

After various trial and errors, this is the code that I landed on. Even to me, the code seems very clunky esp in the searchPantry JSX element that is using the func as a prop (:worried:).

In any case, the console.logs show that the func returns empty array so sibling component does not get the information that it needs.


Help! And thanks!

The setup that I provided in previous post is valid and will work. Problem is in your application logic in general.

I would recommend writing the entire app from scratch. First take a pen and paper (or white/blackboard - whatever you prefer) and sketch out your end goal. Plan the communication between the components and their dependencies. Then write the simplest implementation that satisfies your requirements. Start with hardcoded values. Only when you have the application foundation laid out and data moves correctly, start writing the logic that parses and combines recipes.

Cheers :sparkler: