More HOCs with Recompose
explore withStateHandlers
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 withNamedToggler = propertyName => withStateHandlers(
{ [`${propertyName}IsActive`] : false },
{
[`${propertyName}Toggler`] : props => (e) => {
return { [`${propertyName}IsActive`]: !props[`${propertyName}IsActive`] };
}
}
);
const withMyThingToggler = withNamedToggler("myThing");
const SimpleComponent = ({myThingIsActive, myThingToggler}) => {
return (
<div onClick={ myThingToggler }>
{ myThingIsActive ? <h1>Simple Active</h1> : <h1>Simple Not active</h1> }
</div>
)
};
const SimpleWithState = withMyThingToggler(SimpleComponent);
const OtherSimpleComponent = ({myThingIsActive, myThingToggler, myOtherThingIsActive, myOtherThingToggler}) => {
return (
<div>
<div onClick={ myThingToggler }>
{ myThingIsActive ? <h1>First Active</h1> : <h1>First Not active</h1> }
</div>
<div onClick={ myOtherThingToggler }>
{ myOtherThingIsActive ? <h1>Second Active</h1> : <h1>Second Not active</h1> }
</div>
</div>
);
};
const withMyOtherThingToggler = withNamedToggler("myOtherThing");
const withBothOfMyThings = compose(withMyThingToggler, withMyOtherThingToggler);
const OtherSimpleWithState = withBothOfMyThings(OtherSimpleComponent);
const App = () => {
return (
<div>
<SimpleWithState />
<hr/>
<OtherSimpleWithState />
</div>
);
};
ReactDOM.render(<App />, document.getElementById('root'));