Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pass setState from parent to its child component using React Hook

How do I pass setState from parent to its child component using React Hooks? Code is provided:

App.js

export default App() {
  <Main>
    <Widget/>
  </Main>
}

Main.js

export default Main() {
  const [marketProducts, setMarketProducts] = useState([]);
  ...
  return 
    <DataContext.Provider value={marketProducts}>
      ...
      {props.children}
    </DataContext.Provider>;
}

Widget.js

export default Widget() {
  return <div>
    <NavComponent/>
    ...
  </div>
}

NavComponent.js

export default NavComponent() {
  // need setMarketProducts here but not sure how to bring from Main.js to here
  return <div>
    ...
  </div>
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can pass setMarketProducts down the chain as shown in example below. Other wise you can use some kind of store e.g. useContext or redux

export default App() {
  const [marketProducts, setMarketProducts] = useState([]);
  <Main setMarketProducts={setMarketProducts} marketProducts={marketProducts}>
    <Widget setMarketProducts={setMarketProducts}/>
  </Main>
}

export default Main({ setMarketProducts,marketProducts, ...props }) {

  ...
  return 
    <DataContext.Provider value={marketProducts}>
      ...
      {props.children}
    </DataContext.Provider>;
}


export default Widget({ setMarketProducts }) {
  return <div>
    <NavComponent setMarketProducts={setMarketProducts}/>
    ...
  </div>
}

export default NavComponent({ setMarketProducts }) {
  // need setMarketProducts here but not sure how to bring from Main.js to here
  return <div>
    ...
  </div>
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading