Skip to content

Instantly share code, notes, and snippets.

@weeksie
Last active October 31, 2021 00:31
Show Gist options
  • Save weeksie/10caea04286dc2f0ea5b0db42521d9f2 to your computer and use it in GitHub Desktop.
Save weeksie/10caea04286dc2f0ea5b0db42521d9f2 to your computer and use it in GitHub Desktop.
Using a provider to render content into a sibling or parent
const Editor = () => {
// ...
useTopBarContent(
<ValidationBar />
);
return (
// ...
);
};
const TopBar = () => {
//...
const { content } = useContext(TopBarContext);
//...
return (
<AppBar position="fixed">
<NavMenu />
{content}
<AccountMenu />
</AppBar>
);
};
import React, { createContext, useState, useContext, useEffect } from 'react';
type TopBarContent = React.ReactNode | null;
type TopBarContentState = {
content: TopBarContent;
setTopBarContent: (c: TopBarContent) => void;
};
export const TopBarContext = createContext<TopBarContentState>({
content: null,
setTopBarContent: () => {},
});
export const useTopBarContent = (c: TopBarContent) => {
const {
setTopBarContent
} = useContext(TopBarContext);
useEffect(() => {
setTopBarContent(c);
return () => {
setTopBarContent(null);
};
}, []);
};
type Props = {
children: React.ReactNode;
};
const TopBarProvider = ({ children }: Props) => {
const [content, setTopBarContent] = useState<TopBarContent>(null);
return (
<TopBarContext.Provider value={{ content, setTopBarContent }}>
{children}
</TopBarContext.Provider>
)
};
export default TopBarProvider;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment