Photo by Zoltan Tasi on Unsplash

Using React Portals for cleaner components

Osman Cea
5 min readOct 16, 2023

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…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Osman Cea

Senior Software Engineer | Web Development