Brandon Brandon - 3 months ago 11
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,
onChange
would dispatch an action to update the
store
, 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
    onChange
    events

  2. Since the slider itself isn't connected to the
    store
    , every
    onChange
    forces a re-render on the parent, as
    props
    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
    onChange
    events.

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



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

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

https://facebook.github.io/react/docs/component-specs.html#updating-componentwillreceiveprops