'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 1:[1]
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>
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Someone Special |
