0

How can I render multiple components in single route in react-router-dom v6?

This is how I render in react-router-dom v5

function App() {
  return (
    <Router>
      <div className="app">
        <Switch>
          <Route path="/checkout">
            <Header />
            <Checkout />
          </Route>
          <Route path="/">
            <Header />
            <Home />
          </Route>
        </Switch>
      </div>
    </Router>
  );
}

How can I do same thing with react-router-dom v6?

2 Answers 2

1

It's basically done the same way, but returning a single JSX node on the Route component's element prop.

Example:

function App() {
  return (
    <div className="app">
      <Routes>
        <Route
          path="/"
          element={(
            <>
              <Header />
              <Home />
            </>
          )}
        />
        <Route
          path="/checkout"
          element={(
            <>
              <Header />
              <Checkout />
            </>
          )}
        />
      </Routes>
    </div>
  );
}

In the case where you are wanting to render the Header with several routes then the recommended suggestion is to render what are called Layout Routes that render common logic and UI, and an Outlet component for nested routes to render their element into.

Example:

import { Outlet } from 'react-router-dom';

export const Layout = () => (
  <>
    <Header />
    <Outlet />
  </>
);

...

function App() {
  return (
    <div className="app">
      <Routes>
        <Route element={<Layout />}>
          <Route path="/" element={<Home />} />
          <Route path="/checkout" element={<Checkout />} />
        </Route>
      </Routes>
    </div>
  );
}
Sign up to request clarification or add additional context in comments.

Comments

0

you need to change Switch for Routes

const Home = () => (
  <> 
   <Header /> 
   <Checkout /> 
  </>
)
<BrowserRouter>
  <Routes>
    <Route path="/" element={<Home />} />
  </Routes>
</BrowserRouter>

you can create a new component for reuse header in both elements

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.