Brandon Brandon - 1 year ago 184
React JSX Question

How can I set state in a child component from a parent?

I have a slider component nested in a form in my app. The slider adjusts parameters that live in a

Redux store

Normally, the slider would be controlled, its values set by the props passed down from the
Redux store
. When the slider is moved,
would dispatch an action to update the
, and the slider values would change.

However, in this case, this solution poses problems:

  1. The slider has 100+ steps, so dragging it 50% across means dozens
    and dozens of

  2. Since the slider itself isn't connected to the
    , every
    forces a re-render on the parent, as
    are changing. This eviscerates performance.

So, I've implemented a partial solution:

  1. the slider values live in the slider's state, so dragging it just re-renders the slider with

  2. an
    event--which fires when the user releases the mouse after dragging the slider,
    es the new values to the

However, the parent has a "reset" button that should set the slider's values to their initial state.

So, how can I communicate to the slider component from the parent that it's time to reset values?

Answer Source

Have your parent's reset button do whatever it needs to do to update the store. When store changes, the updated value will be used as new props.

You can then define the reset logic with componentWillReceiveProps on your Slider component

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