Home > Mobile >  How to send data from one react component to another react component?
How to send data from one react component to another react component?

Time:01-22

Here I get some data from the 'Order' component and then I want to send this data to Navigate but all I get when using 'props.order_data' in 'Navigate' is undefined. How can I use this data in 'Navigate'?

function App(){

  function getData(some){
    console.log(some);
    return(<Navigate order_data= {some}/>);
  }
  return(
    <div>
      <Navigate />
      <Service/>
      <Order onAdd={getData}/>
      <Review />
      <Foot />
  </div>
  );
}
export default App;

CodePudding user response:

What you are trying to do won't work as the return-value of the getData function is passed to the Order-component's onAdd function.

I would suggest that you create a state for the order_data in your App-component and pass the state as a prop to the Navigate-element that you are returning. You will need to update the state as soon as you retrieve the data (e.g. in getData function).

React will take care of updating the component as soon as the state changes.

See React documentation for more details: https://reactjs.org/docs/lifting-state-up.html

CodePudding user response:

You need to use useState hook to maintain a state. Since you have your Navigate and Order component in the same Parent App.

Do like this

 import { useState } from "react";

 function App(){

  const [some, setSome] = useState(null); // Initial some value is null

  function getData(data){
    setSome(data); // This will update some state value
  }
  return(
    <div>
      <Navigate order_data={some}/> 
      <Service/>
      <Order onAdd={getData}/>
      <Review />
      <Foot />
  </div>
  );
}
export default App;
  •  Tags:  
  • Related