Skip to content

Commit c35acd5

Browse files
committed
Port buildContext to TS
Unclutter dropdown-context
1 parent 5fae368 commit c35acd5

File tree

3 files changed

+36
-42
lines changed

3 files changed

+36
-42
lines changed

src/app/components/jsx-helpers/build-context.js

-28
This file was deleted.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import React from 'react';
2+
3+
export default function buildContext<P, V>({
4+
defaultValue = {} as V,
5+
useContextValue
6+
}: {
7+
defaultValue?: V;
8+
useContextValue: (p: P) => V;
9+
}) {
10+
const Context = React.createContext(defaultValue);
11+
12+
function useContext() {
13+
return React.useContext(Context);
14+
}
15+
16+
function ContextProvider({
17+
children,
18+
contextValueParameters = undefined as P
19+
}: React.PropsWithChildren<{
20+
contextValueParameters?: P;
21+
}>) {
22+
const value = useContextValue(contextValueParameters);
23+
24+
if (value === undefined) {
25+
return null;
26+
}
27+
28+
return <Context.Provider value={value}>{children}</Context.Provider>;
29+
}
30+
31+
return {useContext, ContextProvider};
32+
}
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
import React from 'react';
21
import buildContext from '~/components/jsx-helpers/build-context';
2+
import {useState} from 'react';
33

44
function useContextValue({prefix} = {prefix: 'menulabel'}) {
5-
const [activeDropdown, setActiveDropdown] = React.useState({});
6-
const [submenuLabel, setSubmenuLabel] = React.useState();
5+
const [activeDropdown, setActiveDropdown] = useState({});
6+
const [submenuLabel, setSubmenuLabel] = useState();
77

88
return {
99
activeDropdown,
@@ -16,14 +16,4 @@ function useContextValue({prefix} = {prefix: 'menulabel'}) {
1616

1717
const {useContext, ContextProvider} = buildContext({useContextValue});
1818

19-
type Arg = {
20-
prefix: string;
21-
};
22-
type DDCPArgs = React.PropsWithChildren<{
23-
contextValueParameters?: Arg;
24-
}>;
25-
const DropdownContextProvider = ContextProvider as (
26-
args: DDCPArgs
27-
) => JSX.Element;
28-
29-
export {useContext as default, DropdownContextProvider};
19+
export {useContext as default, ContextProvider as DropdownContextProvider};

0 commit comments

Comments
 (0)