From ebdeee342f484ca292bfcd32862255dec319a975 Mon Sep 17 00:00:00 2001 From: George Mamadashvili Date: Thu, 3 Aug 2023 16:27:05 +0400 Subject: [PATCH] Plugins: Introduce the 'usePluginContext' hook (#53291) --- packages/plugins/README.md | 8 ++++++++ packages/plugins/src/components/index.js | 2 +- .../src/components/plugin-context/index.tsx | 19 ++++++++++++++----- 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/packages/plugins/README.md b/packages/plugins/README.md index 99bfd3d7bd74d..a0e8441513e5d 100644 --- a/packages/plugins/README.md +++ b/packages/plugins/README.md @@ -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. diff --git a/packages/plugins/src/components/index.js b/packages/plugins/src/components/index.js index dae012a5cadef..12a9a96808bc6 100644 --- a/packages/plugins/src/components/index.js +++ b/packages/plugins/src/components/index.js @@ -1,2 +1,2 @@ export { default as PluginArea } from './plugin-area'; -export { withPluginContext } from './plugin-context'; +export { usePluginContext, withPluginContext } from './plugin-context'; diff --git a/packages/plugins/src/components/plugin-context/index.tsx b/packages/plugins/src/components/plugin-context/index.tsx index fe4fa4cecfa07..76fbdabe04829 100644 --- a/packages/plugins/src/components/plugin-context/index.tsx +++ b/packages/plugins/src/components/plugin-context/index.tsx @@ -1,7 +1,7 @@ /** * WordPress dependencies */ -import { createContext } from '@wordpress/element'; +import { createContext, useContext } from '@wordpress/element'; import { createHigherOrderComponent } from '@wordpress/compose'; /** @@ -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 @@ -39,13 +48,13 @@ export const withPluginContext = ( ) => createHigherOrderComponent( ( OriginalComponent ) => { return ( props ) => ( - + { ( context ) => ( ) } - + ); }, 'withPluginContext' );