recompact v3.3.0
branchconnectObsdebugdefaultPropsflattenProp->flattenPropsflattenPropflattenPropsgetContextlifecyclemapPropsmapPropsStreamnestomitPropsonlyUpdateForKeysonlyUpdateForPropTypespickPropspluckObspurerenameProprenamePropsrenderComponentrenderNothingsetDisplayNamesetPropTypessetStaticshouldUpdatetoClasswithContextwithHandlerswithObswithPropswithPropsOnChangewithReducerwithStatewithStateHandlerswrapDisplayName
componentFromPropcomposecreateEagerElementcreateEagerFactorycreateEventHandlercreateHelpercreateSinkgetDisplayNamehoistStaticsidentityisClassComponentisReferentiallyTransparentFunctionComponent
Set the config of Recompact.
options(Object):
setConfig({observablesKey: 'observables'});Accepts a test function and two higher-order components. The test function is passed the props from the owner. If it returns true, the left higher-order component is applied to BaseComponent; otherwise, the right higher-order component is applied (defaults to identity).
test(Function): The test to apply.left(HigherOrderComponent): The higher-order component applied if the result of the test is true.[right=identity](HigherOrderComponent): The higher-order component applied if the result of the test is false.
(HigherOrderComponent): A function that takes a component and returns a new component.
// Add the logic or rendering nothing if the prop `count` equals to `0`.
branch(({count}) => count === 0, renderNothing)(MyComponent);Connect observables to props using a map.
- The function take one argument, an object containing context observables
and a special observable
props$that emits owner props. - The property is updated at each emission of a new value by the associated Observable.
- Properties matching
/^on[A-Z]/are mapped to thenextmethod of the associated Observer.
obsMapper(Function): The function that takes observables and returns map.
(HigherOrderComponent): A function that takes a component and returns a new component.
connectObs(({change$, value$}) => ({
onChange: change$,
value: value$,
}))('input');Display the flow of props. Very useful for debugging higher-order component stack.
label(*): A label displayed in console.selector(Function): A props selector.
(HigherOrderComponent): A function that takes a component and returns a new component.
recompact.compose(
recompact.withProps({ foo: 'bar' }),
recompact.debug(),
recompact.renameProp('foo', 'className'),
recompact.debug(),
)('input')Specify props values that will be used if the prop is undefined.
defaultProps(Object): Default props.
(HigherOrderComponent): A function that takes a component and returns a new component.
const Button = defaultProps({type: 'button'})('button');
<Button /> // will render <button type="button" />Flattens a prop so that its fields are spread out into the props object.
propName(String): Name of the prop to flatten.
(HigherOrderComponent): A function that takes a component and returns a new component.
const Button = flattenProp('props')('button');
<Button props={{type: 'submit'}} /> // will render <button type="submit" />Flattens one or several props so that its fields are spread out into the props object.
flattenProp
paths(String|String[]): The property paths to flatten.
(HigherOrderComponent): A function that takes a component and returns a new component.
const Button = flattenProps(['a', 'b'])('button');
// Will render <button type="submit" className="btn" />
<Button a={{type: 'submit'}} b={{className: 'btn'}} />Gets values from context and passes them along as props.
contextTypes(Object): Context types to inject as props.
(HigherOrderComponent): A function that takes a component and returns a new component.
// Create a component that will bring back to home when clicked
const HomeButton = compose(
withContext({router: PropTypes.object.isRequired}),
withHandlers({onClick: ({router}) => () => router.push('/')}),
)('button');A higher-order component that permits to hook a lifecycle method. Available methods are:
- componentWillMount
- componentDidMount
- componentWillReceiveProps
- shouldComponentUpdate
- componentWillUpdate
- componentDidUpdate
- componentWillUnmount You should use this helper as an escape hatch, in case you need to access component lifecycle methods.
spec(Object): Lifecycle spec
(HigherOrderComponent): A function that takes a component and returns a new component.
// Create a hoc that will log when a component will mount
const logWhenMount = lifecycle({componentWillMount: () => console.log('will mount')});Accepts a function that maps owner props to a new collection of props that are passed to the base component.
propsMapper(Function): The function that returns new props.
(HigherOrderComponent): A function that takes a component and returns a new component.
// Add a new prop computed from owner props
mapProps(({count}) => ({moreThanFive: count > 5}))(MyComponent);Accepts a function that maps an observable stream of owner props to a stream of child props, rather than directly to a stream of React nodes. The child props are then passed to a base component.
propsStreamMapper(Function):
(HigherOrderComponent): A function that takes a component and returns a new component.
// Delay rendering of 1s
const delayRendering = mapPropsStream(props$ => props$.delay(1000));Composes components by nesting each one inside the previous.
components(...(ReactClass|ReactFunctionalComponent)):
(ReactFunctionalComponent):
// Delay rendering of 1s
const DivButton = nest('div', 'button');
// will render <div className="foo"><button className="foo" /></div>
<DivButton className="foo" />Same as lodash omit but for props.
paths(String|String[]): The property paths to omit.
(HigherOrderComponent): A function that takes a component and returns a new component.
const withoutValue = omitProps('value');Prevents the component from updating unless a prop corresponding to one of the
given keys has updated. Uses shallowEqual() to test for changes.
This is a much better optimization than the popular approach of using PureRenderMixin,
shouldPureComponentUpdate(), or pure() helper, because those
tools compare every prop, whereas onlyUpdateForKeys() only cares about the
props that you specify.
propKeys(String[]): The property keys that will induce a re-render.
(HigherOrderComponent): A function that takes a component and returns a new component.
onlyUpdateForKeys(['value'])Works like onlyUpdateForKeys(), but prop keys are inferred from the propTypes
of the base component. Useful in conjunction with setPropTypes().
If the base component does not have any propTypes, the component will never
receive any updates. This probably isn't the expected behavior, so a warning
is printed to the console.
(HigherOrderComponent): A function that takes a component and returns a new component.
const Button = ({className}) => <button className={className} />;
Button.propTypes = {className: PropTypes.string};
const EnhancedButton = onlyUpdateForPropTypes(Button);Same as lodash pick but for props.
paths(String|String[]): The property paths to pick.
(HigherOrderComponent): A function that takes a component and returns a new component.
const onlyWithValue = pickProps('value');Takes a list of observable names, find the corresponding observables from the context and map them to the corresponding prop according the convention i.e.: same name without a $ at the end.
observablesNames(Function):
(HigherOrderComponent): A function that takes a component and returns a new component.
Prevents the component from updating unless a prop has changed.
Uses shallowEqual() to test for changes.
(HigherOrderComponent): A function that takes a component and returns a new component.
pure('button')Renames a single prop.
oldName(String):newName(String):
(HigherOrderComponent): A function that takes a component and returns a new component.
renameProp('data', 'value')Renames multiple props, using a map of old prop names to new prop names.
nameMap(Object): A map with old prop as key and new prop as value.
(HigherOrderComponent): A function that takes a component and returns a new component.
renameProps({data: 'value'})Takes a component and returns a higher-order component version of that component.
This is useful in combination with another helper that expects a higher-order
component, like branch.
Component(ReactClass|ReactFunctionalComponent|String):
(HigherOrderComponent): A function that takes a component and returns a new component.
const renderLoaderIfLoading = branch(
({loading} => loading),
renderComponent(Loader),
)A higher-order component that always renders null.
(HigherOrderComponent): A function that takes a component and returns a new component.
const renderNothingIfNoRules = branch(
({rules} => rules.length === 0),
renderNothing,
)Assigns to the displayName property on the base component.
displayName(String):
(HigherOrderComponent): A function that takes a component and returns a new component.
setDisplayName('AnotherDisplayName')(MyComponent);Assigns to the propTypes property on the base component.
propTypes(Object):
(HigherOrderComponent): A function that takes a component and returns a new component.
setPropTypes({children: PropTypes.node})(MyComponent);Assigns a value to a static property on the base component.
key(String):value(String):
(HigherOrderComponent): A function that takes a component and returns a new component.
setStatic({defaultProps: {type: 'button'}})('button');Higher-order component version of
shouldComponentUpdate().
The test function accepts both the current props and the next props.
test(Function): Receive two arguments, props and nextProps
(HigherOrderComponent): A function that takes a component and returns a new component.
// Pure
shouldUpdate((props, nextProps) => shallowEqual(props, nextProps))Takes a function component and wraps it in a class. This can be used as a fallback for libraries that need to add a ref to a component, like Relay. If the base component is already a class, it returns the given component.
(HigherOrderComponent): A function that takes a component and returns a new component.
const Component = toClass(() => <div />);
<Component ref="foo" /> // A ref can be used because Component is a classProvides context to the component's children. childContextTypes is an object
of React prop types. getChildContext() is a function that returns
the child context. Use along with getContext().
childContextTypes(Object):getChildContext(Function):
(HigherOrderComponent): A function that takes a component and returns a new component.
// Provide window in the context, useful for testing
const withWindow = withContext({window: PropTypes.object.isRequired}, () => {window})Takes an object map of handler creators or a factory function. These are
higher-order functions that accept a set of props and return a function handler:
This allows the handler to access the current props via closure, without needing
to change its signature.
Handlers are passed to the base component as immutable props, whose identities
are preserved across renders. This avoids a common pitfall where functional
components create handlers inside the body of the function, which results in a
new handler on every render and breaks downstream shouldComponentUpdate()
optimizations that rely on prop equality.
handlerFactories(Function|Object):
(HigherOrderComponent): A function that takes a component and returns a new component.
const enhance = compose(
withState('value', 'updateValue', ''),
withHandlers({
onChange: props => event => {
props.updateValue(event.target.value)
},
onSubmit: props => event => {
event.preventDefault()
submitForm(props.value)
}
})
)
const Form = enhance(({ value, onChange, onSubmit }) =>
<form onSubmit={onSubmit}>
<label>Value
<input type="text" value={value} onChange={onChange} />
</label>
</form>
)Takes observables from the context and special observable props$ and map them
to a new set of observables.
obsMapper(Function): The function that take previous observables and returns new ones.
(HigherOrderComponent): A function that takes a component and returns a new component.
const withFullName$ = mapObs(({firstName$, props$}) => ({
fullName$: Observable.combineLatest(
firstName$,
props$.pluck('lastName'),
(firstName, lastName) => `${firstName} ${lastName}`
)
}))Like mapProps(), except the newly created props are merged with the owner props.
Instead of a function, you can also pass a props object directly. In this form,
it is similar to defaultProps(), except the provided props take precedence over
props from the owner.
propsMapper(Function|Object):
(HigherOrderComponent): A function that takes a component and returns a new component.
const Button = withProps({type: 'button'})('button');
const XButton = withProps(({type}) => {type: `x${type}`})('button');Like withProps(), except the new props are only created when one of the owner
props specified by shouldMapOrKeys changes. This helps ensure that expensive
computations inside createProps() are only executed when necessary.
Instead of an array of prop keys, the first parameter can also be a function
that returns a boolean, given the current props and the next props. This allows
you to customize when createProps() should be called.
shouldMapOrKeys(Function|String|String[]):createProps(Function):
(HigherOrderComponent): A function that takes a component and returns a new component.
const withEmptyProp = withPropsOnChange('count', ({count}) => ({empty: count === 0}));Similar to withState(), but state updates are applied using a reducer function.
A reducer is a function that receives a state and an action, and returns a new state.
Passes two additional props to the base component: a state value, and a
dispatch method. The dispatch method sends an action to the reducer, and
the new state is applied.
stateName(String):dispatchName(String):reducer(Function):initialState(*):
(HigherOrderComponent): A function that takes a component and returns a new component.
const counterReducer = (count, action) => {
switch (action.type) {
case INCREMENT:
return count + 1
case DECREMENT:
return count - 1
default:
return count
}
}
const enhance = withReducer('counter', 'dispatch', counterReducer, 0)
const Counter = enhance(({ counter, dispatch }) =>
<div>
Count: {counter}
<button onClick={() => dispatch({ type: INCREMENT })}>Increment</button>
<button onClick={() => dispatch({ type: DECREMENT })}>Decrement</button>
</div>
)Passes two additional props to the base component: a state value, and a function to update that state value. The state updater has the following signature:
stateUpdater<T>((prevValue: T) => T): void
stateUpdater(newValue: any): voidThe first form accepts a function which maps the previous state value to a new
state value. You'll likely want to use this state updater along with withHandlers()
or withProps() to create specific updater functions. For example, to create an
HoC that adds basic counting functionality to a component:
const addCounting = compose( withState('counter', 'setCounter', `0`), withProps(({ setCounter }) => *({ increment: () => setCounter(n => n + `1`), decrement: () => setCounter(n => n - `1`), reset: () => setCounter(0) }))*
)The second form accepts a single value, which is used as the new state. An initial state value is required. It can be either the state value itself, or a function that returns an initial state given the initial props.
stateName(String):stateUpdaterName(String):initialState(*|Function):
(HigherOrderComponent): A function that takes a component and returns a new component.
Passes state object properties and immutable updater functions in a form of
(...payload: any[]) => Object to the base component.
Every state updater function accepts state, props and payload and must return
a new state or undefined. The new state is shallowly merged with the previous
state.
initialState(Function|Object):stateUpdaters(Object):
(HigherOrderComponent): A function that takes a component and returns a new component.
const Counter = withStateHandlers(
({ initialCounter = 0 }) => ({
counter: initialCounter,
}),
{
incrementOn: ({ counter }) => (value) => ({
counter: counter + value,
}),
decrementOn: ({ counter }) => (value) => ({
counter: counter - value,
}),
resetCounter: (_, { initialCounter = 0 }) => () => ({
counter: initialCounter,
}),
}
)(
({ counter, incrementOn, decrementOn, resetCounter }) =>
<div>
<Button onClick={() => incrementOn(2)}>Inc</Button>
<Button onClick={() => decrementOn(3)}>Dec</Button>
<Button onClick={resetCounter}>Reset</Button>
</div>
)Returns a wrapped version of a React component's display name. For instance,
if the display name of component is 'Post', and wrapperName is 'mapProps',
the return value is 'mapProps(Post)'. Most Recompose higher-order components
use wrapDisplayName().
component(ReactClass|ReactFunctionalComponent): ComponentwrapperName(String): Wrapper name
(String): Returns a wrapped displayName of the component.
// Create a hoc that will log when a component will mount
wrapDisplayName(Button, 'wrap'); // will return wrap(Button)Creates a component that accepts a component as a prop and renders it with the remaining props.
prop(String): The prop to render as Component.
(ReactFunctionalComponent): Returns a Component.
const enhance = defaultProps({component: 'button'});
const Button = enhance(componentFromProp('component'));
<Button foo="bar" /> // renders <button foo="bar" />
<Button component="a" foo="bar" /> // renders <a foo="bar" />
<Button component={Link} foo="bar" /> // renders <Link foo="bar" />This method is similar to lodash flowRight. It permits to easily compose
several high order components.
[funcs](...Function): The functions to invoke.
(Function): Returns the new composite function.
const enhance = compose(pure, withProps({foo: 'bar'}));
const Component = enhance(MyComponent);React elements are lazily evaluated. But when a higher-order component renders a functional component, the laziness doesn't have any real benefit. createEagerElement() is a replacement for React.createElement() that checks if the given component is referentially transparent. If so, rather than returning a React element, it calls the functional component with the given props and returns its output.
type(ReactClass|ReactFunctionalComponent|String): The type of component to render.[props](Object): The props of the component.[children](ReactNode): The children of the component.
(ReactElement): Returns a element.
createEagerElement('div', {className: 'foo'});The factory form of createEagerElement().
Given a component, it returns a factory.
type(ReactClass|ReactFunctionalComponent|String): The type of component to render.
(Function): Returns a function that take two arguments (props, children) and create an element of the given type.
const div = createFactory('div');
div({className: 'foo'});Returns an object with properties handler and stream. stream is an observable sequence, and handler is a function that pushes new values onto the sequence. Useful for creating event handlers like onClick.
(Object): eventHandler
const {handler, stream} = createEventHandler();Utility method that gives to higher-order components a comprehensive display name.
hoc(HigherOrderComponent): Higher-order component to wrap.helperName(String): Name used to create displayName.[noArgs=false](Boolean): Indicate if the higher-order component has some arguments.
(HigherOrderComponent): Returns a wrapped hoc.
const pluckOnChangeTargetValue = createHelper(
withHandlers({
onChange: ({onChange}) => ({target: {value}}) => onChange(value),
}),
'pluckOnChangeTargetValue',
);
const Input = pluckOnChangeTargetValue('input');
<Input /> // Will have "pluckOnChangeTargetValue(input)" as displayNameCreates a component that renders nothing (null) but calls a callback when receiving new props.
callback(Function): Function called when new props are received.
(ReactClass): Returns a ReactClass.
const LocationUpdater = createSink(({hash}) => {
window.location.hash = hash;
});
<LocationUpdater hash="foo" /> // Will add "#foo" in the urlReturns the display name of a React component. Falls back to 'Component'.
component(ReactClass|ReactFunctionalComponent):
(String): Returns the display name of the provided component.
const MyButton = () => <button />;
MyButton.displayName = 'MyButton';
getDisplayName(MyComponent); // Will return "MyButton"Augments a higher-order component so that when used, it copies non-react static properties from the base component to the new component. This is helpful when using Recompose with libraries like Relay. Note that this only hoists non-react statics. The following static properties will not be hoisted: childContextTypes, contextTypes, defaultProps, displayName, getDefaultProps, mixins, propTypes, and type. The following native static methods will also be ignored: name, length, prototype, caller, arguments, and arity
hoc(HigherOrderComponent):
(HigherOrderComponent): A function that takes a component and returns a new component.
hoistStatics(withProps({foo: 'bar'}));This method is similar to lodash identity. It returns the first argument it receives.
value(*): Any value
(*): Returns value
identity(Component) === ComponentReturns true if the given value is a React component class.
value(*): Any value
(Boolean): Returns true if the given value is a React component class.
const Nothing = () => null;
const Nothing2 = class extends Component { render() { return null; } };
const Nothing3 = React.createClass({ render() { return null; } });
isClassComponent(Nothing); // false
isClassComponent(Nothing2); // true
isClassComponent(Nothing3); // trueReturns true if the given value is a referentially transparent function component. A referentially transparent function component is a component without any other thing expect taking some props and returning a component. This method is useful to apply some optimization.
value(*): Any value
(Boolean): Returns true if the given value is a referentially transparent function component.
const Button = () => <button />;
isReferentiallyTransparentFunctionComponent(Button); // true