Skip to content

Commit

Permalink
Plugins: Introduce the 'usePluginContext' hook (#53291)
Browse files Browse the repository at this point in the history
  • Loading branch information
Mamaduka authored Aug 3, 2023
1 parent 00a1b6e commit ebdeee3
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 6 deletions.
8 changes: 8 additions & 0 deletions packages/plugins/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,14 @@ _Returns_

- `WPPlugin | undefined`: The previous plugin settings object, if it has been successfully unregistered; otherwise `undefined`.

#### usePluginContext

A hook that returns the plugin context.

_Returns_

- `PluginContext`: Plugin context

#### withPluginContext

A Higher Order Component used to inject Plugin context to the wrapped component.
Expand Down
2 changes: 1 addition & 1 deletion packages/plugins/src/components/index.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export { default as PluginArea } from './plugin-area';
export { withPluginContext } from './plugin-context';
export { usePluginContext, withPluginContext } from './plugin-context';
19 changes: 14 additions & 5 deletions packages/plugins/src/components/plugin-context/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* WordPress dependencies
*/
import { createContext } from '@wordpress/element';
import { createContext, useContext } from '@wordpress/element';
import { createHigherOrderComponent } from '@wordpress/compose';

/**
Expand All @@ -14,12 +14,21 @@ export interface PluginContext {
icon: null | WPPlugin[ 'icon' ];
}

const { Consumer, Provider } = createContext< PluginContext >( {
const Context = createContext< PluginContext >( {
name: null,
icon: null,
} );

export { Provider as PluginContextProvider };
export const PluginContextProvider = Context.Provider;

/**
* A hook that returns the plugin context.
*
* @return {PluginContext} Plugin context
*/
export function usePluginContext() {
return useContext( Context );
}

/**
* A Higher Order Component used to inject Plugin context to the
Expand All @@ -39,13 +48,13 @@ export const withPluginContext = (
) =>
createHigherOrderComponent( ( OriginalComponent ) => {
return ( props ) => (
<Consumer>
<Context.Consumer>
{ ( context ) => (
<OriginalComponent
{ ...props }
{ ...mapContextToProps( context, props ) }
/>
) }
</Consumer>
</Context.Consumer>
);
}, 'withPluginContext' );

0 comments on commit ebdeee3

Please sign in to comment.