简体   繁体   中英

React-router-dom doesn't work (renders only a blank page)

I have installed react-router-dom^6.1.0 in my project, but nothing is rendering (I see only blank screen when starting project). Here is the code:

    import './main.global.css'
import {Container, Div} from './styles'
import { Header } from "./components/Header";
import Footer from "./components/Footer";
import {BrowserRouter as Router, Route, Routes} from 'react-router-dom'
import RouterView from './routes'

import AboutPage from "./pages/AboutPage";
import CalendarPage from "./pages/CalendarPage";
import LibraryPage from "./pages/LibraryPage";
import MainPage from './pages/MainPage'
import MediaPage from "./pages/MediaPage";
import PrizePage from "./pages/PrizePage";
import ProjectsPage from "./pages/ProjectsPage";

function App() {
  return (
    <Router>
        <Div>
        <Header />
        <Container>
            <Routes>
              <Route path='/' exact element={<MainPage />} />
              <Route path='/about' element={<AboutPage />} />
              <Route path='/library' element={<LibraryPage />} />
              <Route path='/projects' element={<ProjectsPage />} />
              <Route path='/prize' element={<PrizePage />} />
              <Route path='/media' element={ <MediaPage />} />
              <Route path='/calendar' element={<CalendarPage />} />
            </Routes>
        </Container>
        <Footer />
      </Div>
    </Router>
  );

Removing the exact prop from your first route will fix the problem.

Since react-router-dom v6, there is no need to pass the exact prop. By default, react router will always look for the exact path we pass.

So, your code should look like this:

function App() {
  return (
    <Router>
        <Div>
        <Header />
        <Container>
            <Routes>
              <Route path='/' element={<MainPage />} />
              <Route path='/about' element={<AboutPage />} />
              <Route path='/library' element={<LibraryPage />} />
              <Route path='/projects' element={<ProjectsPage />} />
              <Route path='/prize' element={<PrizePage />} />
              <Route path='/media' element={ <MediaPage />} />
              <Route path='/calendar' element={<CalendarPage />} />
            </Routes>
        </Container>
        <Footer />
      </Div>
    </Router>
  );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM