diff --git a/packages/chart/src/ChartThemeProviderUtils.tsx b/packages/chart/src/ChartThemeProviderUtils.tsx new file mode 100644 index 0000000000..02042d70ac --- /dev/null +++ b/packages/chart/src/ChartThemeProviderUtils.tsx @@ -0,0 +1,50 @@ +/* eslint-disable react/jsx-props-no-spreading */ +import { + ComponentType, + ForwardedRef, + forwardRef, + PropsWithoutRef, + RefAttributes, + useContext, +} from 'react'; +import { ChartTheme } from './ChartTheme'; + +import { + ChartThemeContext, + ChartThemeContextValue, +} from './ChartThemeProvider'; + +/** + * Hook to get the current `ChartThemeContextValue`. + */ +export function useChartTheme(): ChartThemeContextValue | null { + return useContext(ChartThemeContext); +} + +export function withChartTheme

( + Component: ComponentType

+): React.ForwardRefExoticComponent & RefAttributes> & { + WrappedComponent?: ComponentType

; +} { + function WithChartTheme(props: P, ref: ForwardedRef): JSX.Element { + const chartTheme = useChartTheme(); + + if (chartTheme == null) { + throw new Error( + 'ChartTheme is null, did you forget to wrap your component in a ChartThemeProvider?' + ); + } + + return ; + } + + const WithChartThemeForwardRef: React.ForwardRefExoticComponent< + PropsWithoutRef

& RefAttributes + > & { + WrappedComponent?: ComponentType

; + } = forwardRef(WithChartTheme); + + WithChartThemeForwardRef.WrappedComponent = Component; + + return WithChartThemeForwardRef; +} diff --git a/packages/chart/src/index.ts b/packages/chart/src/index.ts index 81510a4e18..63f891db95 100644 --- a/packages/chart/src/index.ts +++ b/packages/chart/src/index.ts @@ -8,5 +8,5 @@ export { default as MockChartModel } from './MockChartModel'; export { default as Plot } from './plotly/Plot'; export * from './ChartTheme'; export * from './ChartThemeProvider'; -export * from './useChartTheme'; +export * from './ChartThemeProviderUtils'; export { default as isFigureChartModel } from './isFigureChartModel'; diff --git a/packages/chart/src/useChartTheme.ts b/packages/chart/src/useChartTheme.ts deleted file mode 100644 index 3646c8521e..0000000000 --- a/packages/chart/src/useChartTheme.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { useContext } from 'react'; - -import { - ChartThemeContext, - ChartThemeContextValue, -} from './ChartThemeProvider'; - -/** - * Hook to get the current `ChartThemeContextValue`. - */ -export function useChartTheme(): ChartThemeContextValue | null { - return useContext(ChartThemeContext); -} - -export default useChartTheme;