Skip to content

Commit

Permalink
Add explanation and example for compose package
Browse files Browse the repository at this point in the history
Uses info from issue #6220 to add additional details and example for
compose package. Props to @gziolo for initial write up in ticket.

Fixes #6220
  • Loading branch information
mkaz committed Jan 25, 2019
1 parent ab0acc3 commit 48923ab
Showing 1 changed file with 49 additions and 2 deletions.
51 changes: 49 additions & 2 deletions packages/compose/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,52 @@

The `compose` package is a collection of handy [Higher Order Components](https://facebook.github.io/react/docs/higher-order-components.html) (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 world and allows to compose any number of functions. An example that illustrates it for two functions:

```js
const compose = ( f, g ) => x
=> f( g( x ) );
```

Here's a simplified example of **compose** in use from our code, see [plugin-sidebar](https://github.com/WordPress/gutenberg/blob/master/packages/edit-post/src/components/sidebar/plugin-sidebar/index.js) for full code:

Using compose:

```js
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 );
```

Equivalent to the following without compose:

```js
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
Expand All @@ -14,6 +60,8 @@ _This package assumes that your code will run in an **ES2015+** environment. If

## Usage

An example using the HOC `withInstanceId` from the compose package:

```js
import { withInstanceId } from '@wordpress/compose';

Expand All @@ -24,6 +72,5 @@ function WrappedComponent( props ) {
const ComponentWithInstanceIdProp = withInstanceId( WrappedComponent );
```

Refer to each Higher Order Component's README file for more details.
Refer to each Higher Order Component's README file for more details, see [list of components](https://github.com/WordPress/gutenberg/tree/master/packages/compose/src).

<br/><br/><p align="center"><img src="https://s.w.org/style/images/codeispoetry.png?1" alt="Code is Poetry." /></p>

0 comments on commit 48923ab

Please sign in to comment.