11

I'm using MUIv5 and React-Router v6 in my project, in which I want to wrap a layout around my pages, but the pages aren't rendering and all i'm getting is an empty div

This is my App component:

import React from "react";
import { Routes, Route } from "react-router-dom";
import { CssBaseline } from "@mui/material";

import MainLanding from './routes/MainLanding';
import StoreLanding from "./routes/StoreLanding";
import Layout from "./components/Layout";

const App = () =>{
    return(
        <>
            <CssBaseline/>
                <Routes>
                    <Route element={<Layout/>}>
                        <Route path="/" element={<MainLanding/>}/>
                        <Route path="/store" element={<StoreLanding/>}/>
                    </Route>
                </Routes>
        </>
    )
}

export default App

This is the layout component where i'm calling the children via props:

import React from 'react';

const Layout = ({ children }) => {
    return (
        <div>
            {children}
        </div>
    )
}
export default Layout;

Output: empty div renders

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
DooMGuy096
  • 252
  • 1
  • 2
  • 12
  • [Used this video as reference](https://www.youtube.com/watch?v=DSuJLPRsdZQ&list=PL4cUxeGkcC9gjxLvV4VEkZ6H6H4yWuS58&index=12) – DooMGuy096 Jan 25 '22 at 17:22
  • why not wrap the routes in layout directly instead of wrapping it as an element in a route? – Adarsh Jan 25 '22 at 17:41
  • Does this answer your question? [React Router v6 shared layouts](https://stackoverflow.com/questions/70236929/react-router-v6-shared-layouts) – gowthz Jun 22 '22 at 02:45

1 Answers1

9

A layout component should render an Outlet for nested Route components to be rendered into. This is different from wrapper components that consume and render the children prop.

See Layout Routes and Outlet for more details.

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

const Layout = () => {
  return (
    <div>
      <Outlet /> // <-- nested routes rendered here!
    </div>
  )
};

For comparison, wrapper components are used to wrap a child component in the element prop. Example:

<Routes>
  <Route
    path="/"
    element={(
      <Layout>
        <MainLanding />
      </Layout>
    )}
  />
  <Route
    path="/store"
    element={(
      <Layout>
        <StoreLanding />
      </Layout>
    )}
  />
</Routes>
Drew Reese
  • 165,259
  • 14
  • 153
  • 181