React state component (higher-order)
A React higher-order component for abstracting away state
Keep your components simple, testable, and composable by using higher-order components. This higher-order component will abstract state away from components, so you can keep using functional stateless components.
Installation
npm install --save react-state-hoc# or yarn add react-state-hoc
API
withState(initialState, mapSetStateToProps?, mergeProps?)(BaseComponent)
Wraps your BaseComponent
with a stateful component, passing the state into the BaseComponent
as props. By default, state will be spread into the component's props, plus the setState
function is passed through. If you specify a mapSetStateToProps
function, setState
will not be passed through.
Two optional arguments allow you to a) define state creators, and b) customise which props are passed into the BaseComponent
.
-
initialState
can be either:-
An object, to be used as the component's initial state.
BaseComponent -
A function, which maps initial props to initial state.
BaseComponent
-
-
mapSetStateToProps
can be either:-
An object, containing state creators. Each state creator is a function which maps input arguments to new state. State creators are a convenient shorthand which automatically binds
setState
into smaller functions. Functions can also be provided as well as objects: they are supported bysetState
(see https://reactjs.org/docs/react-component.html#setstate)BaseComponent -
A function, mapping
initialProps
andsetState
to state creators.BaseComponentDefault:
setState
-
-
mergeProps
: A function mapping the currentprops
,state
andstateCreators
into theBaseComponent
's props.BaseComponentDefault:
...props ...state ...stateCreators
Example
{ return <button onClick= > Clicked counter times </button> } const mapSetStateToProps = const StatefulButton1 = StatelessButton const StatefulButton2 = StatelessButton ReactDOM