CrazyAlexer
CrazyAlexer

Reputation: 65

React Router createBrowserRouter() not rendering child elements

I want to have a navbar as a root element and then add the homepage as a child element but from what I can see whenever I put an element inside children: [ ] it never gets rendered while it works outside of children.

Here is the code snippet of Index.js:

import ReactDOM from 'react-dom/client';
import './index.css';
import {
  createBrowserRouter,
  RouterProvider,
} from "react-router-dom";
import Navbar from './components/navbar';
import Home from './components/home';

import Assets from './components/assets';
import ErrorPage from "./components/errorPage";
import PathNotFound from './components/pathNotFound';

const router = createBrowserRouter([
  {
    path: "/",
    element: <Navbar />,
    errorElement: <ErrorPage />, 
    children: [
      {
        index: true,
        element: <Home />,
      },
      {
        path: "/assets",
        element: <Assets />,
      },
      {
        path:"*",
        element: <PathNotFound />,
      },
    ]
  },
  
]);

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <RouterProvider router={router} />
  </React.StrictMode>
);

I followed and even copy-pasted from the official documentation for nested elements of ReactRouter...

homepage

Upvotes: 2

Views: 2230

Answers (1)

Drew Reese
Drew Reese

Reputation: 203373

When creating/rendering layout routes, the layout route component necessarily needs to render an Outlet component for the nested routes to render their element content into.

Example:

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

const Navbar = () => {
  ...

  return (
    ... Navbar UI JSX

    <Outlet /> // <-- Nested routes render out here

    ...
  );
};

export default Navbar;

Upvotes: 4

Related Questions