Last active
October 31, 2021 00:31
-
-
Save weeksie/10caea04286dc2f0ea5b0db42521d9f2 to your computer and use it in GitHub Desktop.
Using a provider to render content into a sibling or parent
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Editor = () => { | |
// ... | |
useTopBarContent( | |
<ValidationBar /> | |
); | |
return ( | |
// ... | |
); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const TopBar = () => { | |
//... | |
const { content } = useContext(TopBarContext); | |
//... | |
return ( | |
<AppBar position="fixed"> | |
<NavMenu /> | |
{content} | |
<AccountMenu /> | |
</AppBar> | |
); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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