Yunkai Wang
Yunkai Wang

Reputation: 21

Matched leaf route at location "/" does not have an element or Component

I keep getting the error:

Matched leaf route at location "/" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.

when attempting to route to different screens.

App.js

import './App.css';
import * as React from "react";
import Register from "./pages/Register"
import Login from "./pages/login"
import Write from "./pages/Write"
import Home from "./pages/home"
import Single from "./pages/single"
import Footer from './components/Footer';
import Navbar from './components/navbar';
import "./project.scss"

import {
  createBrowserRouter,
  RouterProvider,
  Route,
  Outlet,
} from "react-router-dom";

const main = () => {
  return (
    <div>
      <Navbar />
      <Outlet />
      <Footer />
    </div>
  )
};

const router = createBrowserRouter([
  {
    path: "/",
    Element: <main />,
    children: [
      {
        path: "/",
        Element: <Home />,
      },
      {
        path: "/post/:id",
        element: <Single />,
      },
      {
        path: "/write",
        element: <Write />,
      },
    ],
  },
  {
    path: "/register",
    element: <Register />,
  },
  {
    path: "/login",
    element: <Login />,
  },

])

function App() {
  return (
    <div className="App">
      <div className='container'>
        <RouterProvider router={router} />
      </div>
    </div>
  );
}

export default App;

I have tried multiple solutions that I have found but none of them have worked yet. I understand that the react-router@6 Route component uses an element prop taking a ReactNode (e.g. JSX) or Component prop taking a React Element, but I am not sure how to fit it to my code.

Upvotes: 1

Views: 661

Answers (1)

Drew Reese
Drew Reese

Reputation: 203333

The RouteObject type has an element prop, not Element.

interface RouteObject {
  path?: string;
  index?: boolean;
  children?: React.ReactNode;
  caseSensitive?: boolean;
  id?: string;
  loader?: LoaderFunction;
  action?: ActionFunction;
  element?: React.ReactNode | null;       // <-- element
  Component?: React.ComponentType | null;
  errorElement?: React.ReactNode | null;
  ErrorBoundary?: React.ComponentType | null;
  handle?: RouteObject["handle"];
  shouldRevalidate?: ShouldRevalidateFunction;
  lazy?: LazyRouteFunction<RouteObject>;
}

In Javascript, identifiers are case-sensitive. Change the Element properties to element.

const router = createBrowserRouter([
  {
    element: <Main />,
    children: [
      {
        path: "/",
        element: <Home />,
      },
      {
        path: "/post/:id",
        element: <Single />,
      },
      {
        path: "/write",
        element: <Write />,
      },
    ],
  },
  {
    path: "/register",
    element: <Register />,
  },
  {
    path: "/login",
    element: <Login />,
  },
]);

Upvotes: 1

Related Questions