HOCs with Recompose

by jonahe

HTML

<script src="https://unpkg.com/[email protected]/dist/react-with-addons.js"></script>
<script src="https://unpkg.com/[email protected]/dist/react-dom.js"></script>
<script src="https://unpkg.com/[email protected]/build/Recompose.js"></script>
<div id="root"></div>

Babel + JSX

const { compose, withStateHandlers, branch } = Recompose;

const withIsActiveState = withStateHandlers(
	{ isActive : false },
  {
  	flipActiveState: props => (e) => {
    		return { isActive: !props.isActive };
    }
  }
);

const withCounterState = withStateHandlers(
  { count: 0 },
  {
    increment: ({ count }) => () => ({ count: count + 1 }),
    decrement: ({ count }) => () => ({ count: count - 1 })
  }
);

/*
const styleOuterOnIsActive = branch(
	props => props.isActive,
  Component => props => <div style={ { backgroundColor: 'green' } }><Component {...props}/></div>,
  Component => props => <div style={ { backgroundColor: 'red' } }><Component {...props}/></div>
);
*/

const styleOuterOnIsActive = (firstStyle, secondStyle) => branch(
	props => props.isActive,
  Component => props => <div style={ firstStyle }><Component {...props}/></div>,
  Component => props => <div style={ secondStyle }><Component {...props}/></div>
);

/*
const withCounterAndSwitchState = compose(withCounterState, withIsActiveState, styleOuterOnActive);
*/

const withCounterAndSwitchState = compose(
	withCounterState, 
  withIsActiveState,
  styleOuterOnIsActive(
  { backgroundColor: 'green', opacity: 1 }, //style  on active
  { backgroundColor: 'red', opacity: 0.5 } // style on inactive
 )
);


const SwitchAndCounter = withCounterAndSwitchState(({isActive, flipActiveState, count, increment, decrement}) => {
	return (
  	<div>
      <h1>Switch</h1>
  	  <button onClick={ flipActiveState }>{ isActive ? 'Active (Click to change)' : 'Not active (Click to change)' }</button>
      
      <h1>Counter</h1>
       <div>
         <span>Count: {count}</span><br/>
         <button onClick={increment}>+</button>
         <button onClick={decrement}>-</button>
  	  </div>
  </div>
  )
});

const App = () => {
  return (
  	<div>
      <SwitchAndCounter />
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById('root'));