Home > Software design >  React Router Doesn't Show Components
React Router Doesn't Show Components

Time:11-13

I want to make a 404 page for a single page React app. This is my current code:

import { BrowserRouter as Router, Route, Routes} from "react-router-dom";

export default function App() {

  return (
    <>
    <Router>
      <Routes>

      <Route path = "/">
        <Navbar/>
        <Home />
        <Experience />
        <Skills />
        <Projects />
        <Contact />
        <Floaters />
        <Cursor />
      </Route>

      <Route path = "*">
        <NotFound/>
      </Route>

      </Routes>
    </Router>
    </>
  );
}

My localhost just shows a blank page. What is wrong here?

Do all of the components need to be a single component for this to work?

CodePudding user response:

You should not define the routes like that in react-router-6, you have to use the element prop

import { BrowserRouter as Router, Route, Routes } from "react-router-dom";

export default function App() {
  return (
    <>
      <Router>
        <Routes>
          <Route path="/" element={<Layout />}></Route>
          <Route path="*" element={<NotFound />}></Route>
        </Routes>
      </Router>
    </>
  );
}

export const Layout = () => {
  return (
    <>
      <Navbar />
      <Home />
      <Experience />
      <Skills />
      <Projects />
      <Contact />
      <Floaters />
      <Cursor />
    </>
  );
};

As for the blank screen, you should check the browser devtools

CodePudding user response:

You have to use element attribute and inside that you can either pass all the components under a single fragment

import { BrowserRouter as Router, Route, Routes} from "react-router-dom";

export default function App() {

  return (
    <>
    <Router>
      <Routes>

      <Route path = "/">
        element={
          <>
            <Navbar/>
            <Home />
            <Experience />
            <Skills />
            <Projects />
            <Contact />
            <Floaters />
            <Cursor />
          </>
        }
      </Route>

      <Route path = "*">
        element={
          <NotFound/>
        }
      </Route>

      </Routes>
    </Router>
    </>
  );
}

or you can pass it as an array

import { BrowserRouter as Router, Route, Routes} from "react-router-dom";

export default function App() {

  return (
    <>
    <Router>
      <Routes>

      <Route path = "/">
        element={
          [
            <Navbar/>,
            <Home />,
            <Experience />,
            <Skills />,
            <Projects />,
            <Contact />,
            <Floaters />,
            <Cursor />
          ]
        }
      </Route>

      <Route path = "*">
        element={[
          <NotFound/>
        ]}
      </Route>

      </Routes>
    </Router>
    </>
  );
}
  • Related