axfg
axfg

Reputation: 65

Passing a state from child component to parent component in React?

I have two components named Food and Order. In the Food component user can select a food. I'm storing the selected food in a state. The Food component is rendered inside Order component. Here user can proceed to order their food.

My question is how to pass the selected food from Food component to Order component?

Upvotes: 0

Views: 318

Answers (3)

hjrshng
hjrshng

Reputation: 1826

React, by design, does not have access to its child state. You have to create a callback and pass it as props to Food:

const Food = ({ onChange }) => {
  const [state, setState] = useState("");

  function handleOnChange(e) {
    setState(e.target.value);
    onChange(e.target.value);
  }

  return (
    <>
      <select onChange={handleOnChange} value={state}>
        <option value="pizza">Pizza</option>
        <option value="burger">Burger</option>
      </select>
      Selected: {state}
    </>
  );
};

const Order = () => {
  function handleOnFoodChange(value) {
    console.log(value);
  }
  return <Food onChange={handleOnFoodChange} />;
};

Edit amazing-noyce-d60t2

Upvotes: 0

KR Tirtho
KR Tirtho

Reputation: 464

You can create an event e.g onFoodSelect in Food component which will get called Everytime user selects a food and pass the selected food as a parameter...

Then listen in the event from Order component

// Food
// ....
return <>
      {items.map(item=>(
         <div key={item+Math.random} onClick= {_=>props.onFoodSelect(item)}>{item}</div>)
      }
     </>
// ....

// Order
// ...
return <Food
             onFoodSelect={item=>{
                  // Do whatever
             }}
           />
// ...

Upvotes: 0

Rohan Bagchi
Rohan Bagchi

Reputation: 711

From your explanation, it looks like the Order component needs access to the state inside its child Food component. This is classic lifting state up IMO.

You need to keep the state representing selected food in the Order component and pass it down as prop.

If this is not what you were looking for, please share the work you have done so far in a codesandbox preferably. Will make it easier to help then :)

Upvotes: 2

Related Questions