score:3

Accepted answer

withHandlers takes a curried / higher order function in order to set the props from other HOC (high order component)'s such as withSate or form it's usage.

Enhanced component example:

import { compose } from 'recompose';
import React from 'react';

const enhance = compose(
  withState('count', 'setCount', 0),
  withHandlers({
    incrementCount: props => event => {
      // props would contain copy prop. 
      props.setCount(props.count + 1)
    },
    otherExample: () => event => {
      // If you didn't need props in your handler
    },
    otherIncrementCountExample: ({ count, setCount }) => () => {
      // you can exclude event also
      setCount(count + 1);
    }
  });

export default IncButton = ({ count, incrementCount, copy }) => (
  <div>
   <button onClick={incrementCount}> {copy} </button>
  </div>
);

Usage:

import React from 'react';
import IncButton from './IncButton';
export default App = () => (
  <div>
    <IncButton copy="Increment Me"/>
  </div>
);

score:0

Found out the answer, my example here is simpler than my component, but I'll do my best to translate my findings... though this isn't tested below.

compose(
  withState('count', 'setCount', 0),
  withHandlers({
    incrementCount: props => event => {
      props.setCount(props.count + 1)
    }
  })

(facepalm), it is as I suspected in my question. withHandlers just automatically defines a function for you that will replace the state param with whatever argument you pass it. It is not a smart function, though useful. It will take whatever argument you give it, and update your HOC's state with that argument. You'd use it like this...

function ComponentToEnhance({someProp="default str", ...props}) {
  return (
    <div>
      <h1>{props.count}</h1>
      <button onClick={props.setCount}/>
    </div>
  );
}

someProp is just there to show use of spread operator if you want some props that have a default or get passed in you want to call out specifically...cheers


Related Query

More Query from same tag