Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Children won't render when using a layout in ReactJS

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

like image 406
DhruvK Avatar asked Mar 15 '26 12:03

DhruvK


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.

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>
like image 124
Drew Reese Avatar answered Mar 17 '26 03:03

Drew Reese



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!