0

How to display <NavLink> components inside the Footer? I cannot place the Footer inside RouterProvider. The Footer component should be displayed on every page.

function App() {
  const router = createMemoryRouter(routes)

  return (
    <>
          <RouterProvider router={router} />    
          <Footer />
    </>
  )
}

I am using React Router 7.9.4.

3
  • 1
    You cannot use router-related components outside the router's context. Commented Nov 27 at 15:51
  • I know, but RouterProvider doesnt allow any children inside. So how to move Footer inside the RouterProvider? Commented Nov 27 at 16:06
  • This works: <MemoryRouter > <Routes> <Route path="/" element={<Home />} /> ... </Routes> <Footer /> </MemoryRouter> But I want to exclude the Footer on one page and need the current path to decide if it is included or excluded. Commented Nov 27 at 16:07

2 Answers 2

1

You can use a layout route for Footer. That way you can include it in every route and also include it in your routes.

https://reactrouter.com/start/declarative/routing#layout-routes

Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.