I have an application where users will click various parts of the application and this will display some kind of configuration options in a drawer to the right.
The solution I've got for this is to have whatever content that is to displayed, to be stored in context. That way the drawer just needs to retrieve its content from context, and whatever parts of that need to set the content, can set it directly via context.
Here's a CodeSandbox demonstrating this.
Key code snippets:
const MainContent = () => {
const items = ["foo", "bar", "biz"];
const { setContent } = useContext(DrawerContentContext);
/**
* Note that in the real world, these components could exist at any level of nesting
*/
return (
<Fragment>
{items.map((v, i) => (
<Button
key={i}
onClick={() => {
setContent(<div>{v}</div>);
}}
>
{v}
</Button>
))}
</Fragment>
);
};
const MyDrawer = () => {
const classes = useStyles();
const { content } = useContext(DrawerContentContext);
return (
<Drawer
anchor="right"
open={true}
variant="persistent"
classes={{ paper: classes.drawer }}
>
draw content
<hr />
{content ? content : "empty"}
</Drawer>
);
};
export default function SimplePopover() {
const [drawContent, setDrawerContent] = React.useState(null);
return (
<div>
<DrawerContentContext.Provider
value={{
content: drawContent,
setContent: setDrawerContent
}}
>
<MainContent />
<MyDrawer />
</DrawerContentContext.Provider>
</div>
);
}
My question is - is this an appropriate use of context, or is this kind of solution likely to encounter issues around rendering/virtual dom etc?
Is there a tidier way to do this? (ie. custom hooks? though - remember that some of the components wanting to do the setttings may not be functional components).