T. Cem Yılmaz T. Cem Yılmaz - 1 year ago 74
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
Answer Source
  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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download