Home > OS >  Why react-router-dom does not work in this code
Why react-router-dom does not work in this code

Time:03-21

I'm studying react app and try to use react-router-dom. I typed the "http://localhost:3000/" in the browser. My expectation is "Home" is displayed in the browser. However, as the browser render this code, nothing is displayed.

import React from 'react';
import './App.css';
import { BrowserRouter, Route, Routes } from 'react-router-dom';

function App() {
  return (
    <>
      <div>
        <BrowserRouter>
          <Routes>
            <Route exact path='/' component={HomePage} />
            <Route path='/Contact' component={ContactPage} />
            <Route path='/About' component={AboutPage} />
            <Route component={NotFoundPage} />
          </Routes>
        </BrowserRouter>
      </div>
    </>
  );
}

function HomePage() {
  return <h2>Home</h2>
}

function ContactPage() {
  return <h2>Contact</h2>
}

function AboutPage() {
  return <h2>About</h2>
}

function NotFoundPage() {
  return <h2>NotFoundPage</h2>
}

export default App;

I have no idea why it does not work correctly.

CodePudding user response:

If you are using router v6, you need use the element prop instead of component. But more importantly you need to instantiate the component (change element={HomePage} to element={< HomePage />}).

See the docs: https://reactrouter.com/docs/en/v6/getting-started/concepts#defining-routes

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

function App() {
  return (
    <>
      <div>
        <BrowserRouter>
          <Routes>
            <Route exact path="/" element={<HomePage />} />
            <Route path="/Contact" element={<ContactPage />} />
            <Route path="/About" element={<AboutPage />} />
            <Route component={<NotFoundPage />} />
          </Routes>
        </BrowserRouter>
      </div>
    </>
  );
}

function HomePage() {
  return <h2>Home</h2>;
}

function ContactPage() {
  return <h2>Contact</h2>;
}

function AboutPage() {
  return <h2>About</h2>;
}

function NotFoundPage() {
  return <h2>NotFoundPage</h2>;
}

export default App;
  • Related