In this article I want to share a simple technique using React Portals for better decoupling of context specific features that live on global contexts.
If that was a mouthful, a quick example will make it clearer.
Lets say we have an application where the header can have a contextual menu, some buttons, links and other things that depend on the page that the user is visiting. Our app structure could look like this:
import React from 'react';
export const App = () => {
return (
<main>
<AppHeader />
<AppRouter>
<Route path="/">
<Home />
</Route>
<Route path="/dashboard">
<Dashboard />
</Route>
<Route path="/me">
<Profile />
</Route>
</AppRouter>
</main>
);
};
Where the AppHeader
component is in charge of rendering all of these things:
import React from 'react';
const AppHeader = () => {
const handleSomething = () => {};
const handleSomethingElse = () => {};
return (
<header>
<nav>
<Link to="/">Home</Link>
<Link to="/dashboard">Dashboard</Link>
<Link to="/me">Profile</Link>
</nav>
<ContextMenu
options={[
{ label: 'Option 1' },
{ label: 'Option 2' },
]}
/>
<Button…