Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router v6 shared layouts

After reading Route layouts I wanted to wrap some elements of my routes with a layout, but leave others without a layout.

Here is the example:

App.jsx

import React from 'react';
import { Routes, BrowserRouter, Route } from 'react-router-dom';

export default function App() {
  return (
    <div>
      <BrowserRouter>
        <Routes>
          <Route path="/" element={<p>Home</p>} />

          <Route element={<div style={{ background: 'red' }} />}>
            <Route path="/login" element={<p>Login</p>} />
          </Route>
        </Routes>
      </BrowserRouter>
    </div>
  );

When I go to / I can see the text "Home", it has no layout.
But when I go to /login nothing renders, it should render the red background layout wrapping the text "Login".

Here is a live code sandbox: https://stackblitz.com/edit/github-hwpla5?devtoolsheight=33&file=src/App.jsx

What I'm doing wrong?
Thanks

like image 457
Icaruk Avatar asked Feb 01 '26 12:02

Icaruk


1 Answers

you have to render an <Outlet /> for inside your layout element to specify where the active child route should be mounted.

<Routes>
  <Route path="/" element={<p>Home</p>} />
  <Route element={<div style={{ background: 'red' }} > <Outlet /> </div>}>
    <Route path="/login" element={<p>Login</p>} />
  </Route>
</Routes>

like image 192
Ahmed Eid Avatar answered Feb 04 '26 01:02

Ahmed Eid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!