Portals with React Context
Portals with React Context
Because Portals are part of the React component tree, they have full access to Context.
Any Context provider that wraps the Portal’s component will work, regardless of physical
DOM location.
Example: Theme Context Inside a Portal
import { createContext, useContext } from 'react';
import { createPortal } from 'react-dom';
const ThemeContext = createContext('light');
function ThemedModal() {
const theme = useContext(ThemeContext); // Works! Even inside a Portal
return createPortal(
<div style={{ background: theme === 'dark' ? '#333' : '#fff', color: theme === 'dark' ? '#fff' : '#000' }}>
<p>Current theme: {theme}</p>
</div>,
document.getElementById('modal-root')
);
}
function App() {
return (
<ThemeContext.Provider value="dark">
<ThemedModal /> {/* Can read 'dark' from context */}
</ThemeContext.Provider>
);
}
This works because React’s context system uses the React component tree
(fiber tree), not the DOM tree. The Portal is still a descendant of the ThemeContext.Provider
in the fiber tree.
