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.

ReactDOM.render(
<div>
<SaveCart />
<ImportCart carts={response.items || []}/>
</div>,
newContainer
);


SaveCart is only a component and renders only a Button which handles a prompt modal asks a name and save it via xhr request.
http://kopy.io/rlzn0

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