Sankar
Sankar

Reputation: 17

react , how can i render multiple components in single route in react-router-dom v6?

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?

Upvotes: 0

Views: 1371

Answers (2)

Drew Reese
Drew Reese

Reputation: 202686

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>
  );
}

Upvotes: 1

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

Upvotes: 0

Related Questions