T. Cem Yılmaz T. Cem Yılmaz - 3 months ago 30
React JSX Question

Update child's state from another child of parent

I have a parent that has two children.

<SaveCart />
<ImportCart carts={response.items || []}/>

SaveCart is only a component and renders only a Button which handles a prompt modal asks a name and save it via xhr request.

ImportCart is another component that renders only a Button which handles a modal dialog of saved carts, and import them on a Shopping Cart functionality.http://kopy.io/mlK5w

The thing I want is if my saved carts are empty, when a cart is saved via SaveCart component I want to update the carts prop or state in ImportCart.

leo leo
  1. You need to have the items stored in the state of parent and pass them as props to SaveCart and ImportCart.

  2. Whenever user saves an item via SaveCart, pass it through a callback to the parent and let the parent modify its items (and add the new one).

  3. This will trigger a state change and rerender of ImportCart.