Children won't render when using a layout in ReactJS

Viewed 547

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

1 Answers

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.

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>
Related