4

I have a Slider component that doesn't handle its own state, instead, it's wrapped in another component called SliderDrag that manages the state and passes down props to the Slider

I'm using withState from recompose library to achieve that.

here is my Slider state initial state

export const getInitialState = () => ({
  min: 0,
  max: 100,
  value: 50,
  step: 1,
  width: 100,
  dragging: false
});

And here is my Higher Order Component from withState()

export const SliderDrag = withState('state', 'onChange', getInitialState())(
  ({state, onChange, action}) => (
  <Slider
  {...state}
  onDragStart={({x}) => {
    onChange(dragStart(x, state));
  }}
  onDrag={({x}) => {
    onChange(drag(x, state));
    action('value')(state.value);
  }}
  onDragEnd={() => {
    onChange(dragEnd(state));
  }}
 />
)
);

And here is how I want to use SliderDrag. I want to pass down props to set my initial state so that I can use this Slider component in different contexts in my app

export const interactive = (action) => (
  <Storypage theme={designerTheme}>
    <SliderDrag width={218} step={1} min={0} max={100} action={action}/>
  </Storypage>
);

Do I need to use compose from recompose library? Any advice or help would be highly appreciated. :)

Moody
  • 352
  • 3
  • 15

1 Answers1

5

With some help I was able to solve my problem.

I should pass a reference to the function that sets the initialState as the last argument to withState(), this way when initialState gets called, I will have access to the props I'm passing to my SliderDrag component

Here is how I refactored this

const initialState = ({min, max, step, width, value}) => {
  debugger;
  return defaults({min, max, step, width, value}, defaultState());
};

export const SliderDrag = withState('state', 'onChange', initialState)(
  ({state, onChange, action}) => (
      <Slider
      {...state}
      ...
      />
  )
);

defaults here just overrides the values I'm passing and gives me a new object as my state.

This makes my component configurable because any other component can use it and pass down props as the initial state

Moody
  • 352
  • 3
  • 15