Package Exports
- @wordpress/compose
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@wordpress/compose) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
Compose
The compose package is a collection of handy Hooks and Higher Order Components (HOCs) you can use to wrap your WordPress components and provide some basic features like: state, instance id, pure...
The compose function is an alias to flowRight from Lodash. It comes from functional programming, and allows you to compose any number of functions. You might also think of this as layering functions; compose will execute the last function first, then sequentially move back through the previous functions passing the result of each function upward.
An example that illustrates it for two functions:
const compose = ( f, g ) => x
=> f( g( x ) );Here's a simplified example of compose in use from Gutenberg's PluginSidebar component:
Using compose:
const applyWithSelect = withSelect( ( select, ownProps ) => {
return doSomething( select, ownProps );
} );
const applyWithDispatch = withDispatch( ( dispatch, ownProps ) => {
return doSomethingElse( dispatch, ownProps );
} );
export default compose(
withPluginContext,
applyWithSelect,
applyWithDispatch
)( PluginSidebarMoreMenuItem );Without compose, the code would look like this:
const applyWithSelect = withSelect( ( select, ownProps ) => {
return doSomething( select, ownProps );
} );
const applyWithDispatch = withDispatch( ( dispatch, ownProps ) => {
return doSomethingElse( dispatch, ownProps );
} );
export default withPluginContext(
applyWithSelect( applyWithDispatch( PluginSidebarMoreMenuItem ) )
);Installation
Install the module
npm install @wordpress/compose --saveThis package assumes that your code will run in an ES2015+ environment. If you're using an environment that has limited or no support for ES2015+ such as IE browsers then using core-js will add polyfills for these methods.
API
For more details, you can refer to each Higher Order Component's README file. Available components are located here.
compose
Composes multiple higher-order components into a single higher-order component. Performs right-to-left function composition, where each successive invocation is supplied the return value of the previous.
Parameters
- hocs
...Function: The HOC functions to invoke.
Returns
Function: Returns the new composite function.
createHigherOrderComponent
Given a function mapping a component to an enhanced component and modifier name, returns the enhanced component augmented with a generated displayName.
Parameters
- mapComponentToEnhancedComponent
HigherOrderComponent< TInnerProps, TOuterProps >: Function mapping component to enhanced component. - modifierName
string: Seed name from which to generated display name.
Returns
HigherOrderComponent< TInnerProps, TOuterProps >: Component class with generated display name assigned.
ifCondition
Higher-order component creator, creating a new component which renders if the given condition is satisfied or with the given optional prop name.
Usage
type Props = { foo: string };
const Component = ( props: Props ) => <div>{ props.foo }</div>;
const ConditionalComponent = ifCondition(
( props: Props ) => props.foo.length !== 0
)( Component );
<ConditionalComponent foo="" />; // => null
<ConditionalComponent foo="bar" />; // => <div>bar</div>;Parameters
- predicate
( props: TProps ) => boolean: Function to test condition.
Returns
HigherOrderComponent< TProps, TProps >: Higher-order component.
pure
Given a component returns the enhanced component augmented with a component only rerendering when its props/state change
Type
SimpleHigherOrderComponent
useAsyncList
React hook returns an array which items get asynchronously appended from a source array. This behavior is useful if we want to render a list of items asynchronously for performance reasons.
Parameters
- list
T[]: Source array.
Returns
T[]: Async array.
useConstrainedTabbing
In Dialogs/modals, the tabbing must be constrained to the content of the wrapper element. This hook adds the behavior to the returned ref.
Usage
import { useConstrainedTabbing } from '@wordpress/compose';
const ConstrainedTabbingExample = () => {
const constrainedTabbingRef = useConstrainedTabbing();
return (
<div ref={ constrainedTabbingRef }>
<Button />
<Button />
</div>
);
};Returns
Object|Function: Element Ref.
useCopyOnClick
Deprecated
Copies the text to the clipboard when the element is clicked.
Parameters
- ref
Object: Reference with the element. - text
string|Function: The text to copy. - timeout
number: Optional timeout to reset the returned state. 4 seconds by default.
Returns
boolean: Whether or not the text has been copied. Resets after the timeout.
useCopyToClipboard
Copies the given text to the clipboard when the element is clicked.
Parameters
- text
text|Function: The text to copy. Use a function if not already available and expensive to compute. - onSuccess
Function: Called when to text is copied.
Returns
RefObject: A ref to assign to the target element.
useDebounce
Debounces a function with Lodash's debounce. A new debounced function will
be returned and any scheduled calls cancelled if any of the arguments change,
including the function to debounce, so please wrap functions created on
render in components in useCallback.
Parameters
- args
...any: Arguments passed to Lodash'sdebounce.
Returns
Function: Debounced function.
useFocusOnMount
Hook used to focus the first tabbable element on mount.
Usage
import { useFocusOnMount } from '@wordpress/compose';
const WithFocusOnMount = () => {
const ref = useFocusOnMount();
return (
<div ref={ ref }>
<Button />
<Button />
</div>
);
};Parameters
- focusOnMount
boolean|string: Focus on mount mode.
Returns
Function: Ref callback.
useFocusReturn
When opening modals/sidebars/dialogs, the focus must move to the opened area and return to the previously focused element when closed. The current hook implements the returning behavior.
Usage
import { useFocusReturn } from '@wordpress/compose';
const WithFocusReturn = () => {
const ref = useFocusReturn();
return (
<div ref={ ref }>
<Button />
<Button />
</div>
);
};Parameters
- onFocusReturn
Function?: Overrides the default return behavior.
Returns
Function: Element Ref.
useInstanceId
Provides a unique instance ID.
Parameters
- object
object: Object reference to create an id for. - prefix
[string]: Prefix for the unique id. - preferredId
[string]: Default ID to use.
Returns
string | number: The unique instance id.
useIsomorphicLayoutEffect
Preferred over direct usage of useLayoutEffect when supporting
server rendered components (SSR) because currently React
throws a warning when using useLayoutEffect in that environment.
useKeyboardShortcut
Attach a keyboard shortcut handler.
Parameters
- shortcuts
string[]|string: Keyboard Shortcuts. - callback
Function: Shortcut callback. - options
WPKeyboardShortcutConfig: Shortcut options.
useMediaQuery
Runs a media query and returns its value when it changes.
Parameters
- query
[string]: Media Query.
Returns
boolean: return value of the media query.
useMergeRefs
Merges refs into one ref callback. Ensures the merged ref callbacks are only
called when it changes (as a result of a useCallback dependency update) or
when the ref value changes. If you don't wish a ref callback to be called on
every render, wrap it with useCallback( ref, [] ).
Dependencies can be added, but when a dependency changes, the old ref
callback will be called with null and the new ref callback will be called
with the same node.
Parameters
- refs
Array<RefObject|RefCallback>: The refs to be merged.
Returns
RefCallback: The merged ref callback.
usePrevious
Use something's value from the previous render. Based on https://usehooks.com/usePrevious/.
Parameters
- value
T: The value to track.
Returns
T|undefined: The value from the previous render.
useReducedMotion
Hook returning whether the user has a preference for reduced motion.
Returns
boolean: Reduced motion preference value.
useRefEffect
Effect-like ref callback. Just like with useEffect, this allows you to
return a cleanup function to be run if the ref changes or one of the
dependencies changes. The ref is provided as an argument to the callback
functions. The main difference between this and useEffect is that
the useEffect callback is not called when the ref changes, but this is.
Pass the returned ref callback as the component's ref and merge multiple refs
with useMergeRefs.
It's worth noting that if the dependencies array is empty, there's not strictly a need to clean up event handlers for example, because the node is to be removed. It is necessary if you add dependencies because the ref callback will be called multiple times for the same node.
Parameters
- callback
Function: Callback with ref as argument. - dependencies
Array: Dependencies of the callback.
Returns
Function: Ref callback.
useResizeObserver
Hook which allows to listen the resize event of any target element when it changes sizes.
Note: useResizeObserver will report null until after first render
Usage
const App = () => {
const [ resizeListener, sizes ] = useResizeObserver();
return (
<div>
{ resizeListener }
Your content here
</div>
);
};Returns
Array: An array of {Element}resizeListenerand {?Object}sizeswith propertieswidthandheight
useThrottle
Throttles a function with Lodash's throttle. A new throttled function will
be returned and any scheduled calls cancelled if any of the arguments change,
including the function to throttle, so please wrap functions created on
render in components in useCallback.
Parameters
- args
...any: Arguments passed to Lodash'sthrottle.
Returns
Function: Throttled function.
useViewportMatch
Returns true if the viewport matches the given query, or false otherwise.
Usage
useViewportMatch( 'huge', '<' );
useViewportMatch( 'medium' );Parameters
- breakpoint
WPBreakpoint: Breakpoint size name. - operator
[WPViewportOperator]: Viewport operator.
Returns
boolean: Whether viewport matches query.
useWarnOnChange
Hook that performs a shallow comparison between the preview value of an object and the new one, if there's a difference, it prints it to the console. this is useful in performance related work, to check why a component re-renders.
Usage
function MyComponent( props ) {
useWarnOnChange( props );
return 'Something';
}Parameters
- object
Object: Object which changes to compare. - prefix
string: Just a prefix to show when console logging.
withGlobalEvents
Deprecated
Higher-order component creator which, given an object of DOM event types and values corresponding to a callback function name on the component, will create or update a window event handler to invoke the callback when an event occurs. On behalf of the consuming developer, the higher-order component manages unbinding when the component unmounts, and binding at most a single event handler for the entire application.
Parameters
- eventTypesToHandlers
Object<string,string>: Object with keys of DOM event type, the value a name of the function on the original component's instance which handles the event.
Returns
Function: Higher-order component.
withInstanceId
A Higher Order Component used to be provide a unique instance ID by component.
Type
PropInjectingHigherOrderComponent< { instanceId: string | number; } >
withSafeTimeout
A higher-order component used to provide and manage delayed function calls that ought to be bound to a component's lifecycle.
Parameters
- OriginalComponent
WPComponent: Component requiring setTimeout
Returns
WPComponent: Wrapped component.
withState
A Higher Order Component used to provide and manage internal component state via props.
Parameters
- initialState
?Object: Optional initial state of the component.
Returns
WPComponent: Wrapped component.
