How to display components outside MemoryRouter in React Router? [duplicate]

1 week ago 15
ARTICLE AD BOX

You can render a component outside of the React container using a portal. This would allow you to render the link in the footer element, while the link would still be under the provider.

You'll have the verify that the DOM element exists before rendering. In this example I'm waiting for the <footer> to render. Only when the footerId is not null I render the portal into it.

const { useState } = React const Content = ({ footerId }) => ( <> <div style={{ border: '2px solid black' }}> <p>I'm in the app.</p> </div> {footerId && ReactDOM.createPortal( <p>I'm in the footer</p>, document.querySelector(`#${footerId}`) )} </> ) const Demo = () => { const [footerId, setFooterId] = useState(null) return ( <> <main><Content footerId={footerId} /></main> <footer id="footer" ref={el => setFooterId(el?.id)}/> </> ) } ReactDOM .createRoot(root) .render(<Demo />) <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.3.1/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.3.1/umd/react-dom.production.min.js"></script> <div id="root"></div>

Ori Drori's user avatar

Read Entire Article