Home > Software design >  No component is being displayed in my reactjs app
No component is being displayed in my reactjs app

Time:12-25

I am trying to build a website using ReactJS. Currently, I have a home page and a navbar. None of these components are displayed when trying to view them inside the browser. I guess the problem sits inside of my router, but i can't really put my finger on it.

These are the two components/pages I want to display:

Home.tsx

import Background from "../components/Background";

export default function Home() {
  return (
    <div>
      <Background />
      <h1>Testing text</h1>
    </div>
  );
}

Navbar.tsx

import Link, { LinkProps } from "../components/Link";

const navElements: LinkProps[] = [
  {
    label: "Configure",
    to: "/Configure",
  },
  {
    label: "Archive",
    to: "/Archive",
  },
  {
    label: "About",
    to: "/About",
  },
  {
    label: "Contact",
    to: "/Contact",
  },
];

export default function Navbar() {
  return (
    <div className="flex font-serif space-x-4">
      {navElements.map((navElement) => (
        <Link {...navElement} key={navElement.label} />
      ))}
    </div>
  );
}

These components are brought together in the Routing.tsx:

import { Route, Routes, BrowserRouter, Outlet } from "react-router-dom";
import Home from "../pages/Home";
import Navbar from "../layout/Navbar";

export default function Routing() {
  return (
    <BrowserRouter>
      <Routes>
        <Route
          element={
            <>
              <Navbar />
              <Outlet />
            </>
          }
        />
        <Route path="home">
          <Route index element={<Home />}></Route>
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

The router is finally put into App.tsx

CodePudding user response:

According to the docs, index routes are displayed on parent element's Outlet component.

In your case parent route doesn't have any element. change into this.

<Route path="home" element={<Home />}>
   //add any index route with element if you want
</Route>

CodePudding user response:

After some trial and error (including @Arjun's answer) it worked with the following line of code (part of Routing.tsx):

<BrowserRouter>
      <Routes>
        <Route
          element={
            <>
              <Navbar />
              <Outlet />
            </>
          }
        >
          <Route index element={<Home />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

  • Related