blob: e54f16b1eacb67dc62da3da3114bcfeddeecb6e2 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
import * as React from 'react';
import App from './app';
export interface IAppContext {
app: App;
}
export const AppContext = React.createContext<IAppContext | undefined>(undefined);
if (process.env.NODE_ENV === 'development') {
AppContext.displayName = 'AppContext';
}
export default function withAppContext<Props>(BaseComponent: React.ComponentClass<Props>) {
// Exclude the IAppContext from props since those are injected props
const wrappedComponent = (props: Omit<Props, keyof IAppContext>) => {
return (
<AppContext.Consumer>
{(context) => {
if (context) {
// Enforce type because Typescript does not recognize that
// (Props ~ IAppContext & IAppContext) is identical to Props.
const mergedProps = ({ ...props, ...context } as unknown) as Props;
return <BaseComponent {...mergedProps} />;
} else {
throw new Error(
'The context value is empty. Make sure to wrap the component in AppContext.Provider.',
);
}
}}
</AppContext.Consumer>
);
};
if (process.env.NODE_ENV === 'development') {
wrappedComponent.displayName =
'withAppContext(' + (BaseComponent.displayName || BaseComponent.name) + ')';
}
return wrappedComponent;
}
|