I am still learning React and I was stuck with this issue.
I need to pass props from parent to two children as this is the way the siblings can communicate with eachother.
I tried to use render to pass the props, but it does not work.
Here the parent component which has cart, setCart, cartCopy and setCartCopy, which is what I need to pass to the children.
function App() {
const (cart, setCart) = useState(());
const (cartCopy, setCartCopy) = useState(())
return (
<div >
<header className="App">
<img className='logo' src={logo} alt='NB' />
<Router>
<Nav />
<Route exact path="/" component={Home} />
<Route exact path="/products" component={Products} render={(props) => <Products {...props} cart={cart} setCart={setCart} cartCopy={cartCopy} setCartCopy={setCartCopy} />} />
<Route exact path="/cart" component={Cart} render={(props) => <Cart {...props} cart={cart} setCart={setCart} cartCopy={cartCopy} setCartCopy={setCartCopy} />} />
<Route exact path="/signin" component={Signin} />
<Route exact path="/register" component={Register} />
</Router>
</header>
</div>
);
}
Here one child component, which needs to recieve from parent in order to use the data:
const Cart = ({ cart, setCart, cartCopy, setCartCopy }) => {
const clearCartItem = (itemID) => {
let cartCopy = (...cart)
cartCopy = cartCopy.filter(item => item._id != itemID);
setCart(cartCopy);
let cartString = JSON.stringify(cartCopy)
localStorage.setItem('cart', cartString)
setCartCopy(cartCopy)
}
Thank you!