Home > Enterprise >  React Router not rendering my children elements inside my layout
React Router not rendering my children elements inside my layout

Time:01-03

here's the app.js file

`

import { Box } from '@mui/material';
import {BrowserRouter, Route, Routes} from 'react-router-dom'

// Components
import Home from './components/Home';
import Layout from './Layout';

const App = () => {
  return (
    <Box>
      <BrowserRouter>
        <Layout>
          <Routes>
            <Route exact path="/" component={Home} />
          </Routes>
        </Layout>
      </BrowserRouter>
    </Box>
  );
}

export default App;

`

and here's the layout

`

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

//components
import Navbar from './components/Navbar';

const Layout = () => {
    return (
        <React.Fragment>
            <Navbar/>
            <Outlet/>
        </React.Fragment>
    );
}

export default Layout;

`

also here the Home Page i want to show as children content inside the layout

`

import React from 'react'
import Movies from './MoviesComponent'

const Home = () => {
  return (
    <>
    hello
    </>
  )
}

export default Home

`

i want to render the child components inside the layout, im having a trouble trying for a while, i was able to do it in a older version of react-router but in v6, things changed so, im trying to do the same but it doesn't work

CodePudding user response:

From what I understand, Outlet is used when you have nested Route. https://reactrouter.com/en/main/components/outlet

That's not the case for your Layout. Try using children:

import React from 'react';

//components
import Navbar from './components/Navbar';

const Layout = ({ children }) => {
    return (
        <React.Fragment>
            <Navbar/>
            {children}
        </React.Fragment>
    );
}

export default Layout;

CodePudding user response:

please use

       import { createBrowserRouter } from 'react-router-dom';
    
    
        const router=createBrowserRouter([
          {
            path:'/',
            element:<Home/>
          },
          {
            path:'/Test',
            element:<Test payload={payload}/>
          }
        ]);
        
        root.render(
        <Layout router={router}>
     </Layout>
);

And inside Layout Component

import { Fragment } from "react"
import { RouterProvider } from "react-router-dom";

const Layout=({router})=>{
    return(<Fragment>
        <RouterProvider router={router}>
 </RouterProvider>
    </Fragment>)
}

Layout.displayName='Layout';

export default Layout;
  • Related