Say I want to design a React context that provides a path, and can be nested any number of times. Like this:
<PathProvider path="foo">
<PathProvider path="bar">
<PathProvider path="baz">
<SomeComponent>
</PathProvider>
</PathProvider>
</PathProvider>
If I call usePath()
(not shown) inside <SomeComponent />
, I should get ["foo", "bar", "baz"]
.
How can I implement this? Here’s an attempt:
export interface PathContext {
path: string
}
export const PathContext = createContext()
export interface PathProviderProps extends React.PropsWithChildren {
path: string
}
export default function PathProvider({
path: thisPath,
children
}: PathProviderProps) {
const {path: parentPath} = useContext(PathContext) as PathContext<C>
const fullPath = parentPath ? `${parentPath}.${thisPath}` : thisPath
return (
<SettingsContext.Provider
value={{path: fullPath}}
>
{children}
</SettingsContext.Provider>
)
}
This works! But, since the topmost provider is still calling useContext
, but has no parent context, it throws a console error in the top-most PathProvider
:
CreateContext.ts:31 Missing context provider (where is ‘path’?)
Is there another way to do this? Can I suppress the error somehow?