简体   繁体   中英

React router dom is not rendering a component

This is my code

function App() {
  return (
    <div className="app">
      <BrowserRouter>
        <Header></Header>
        <Routes>
          <Route path='/' exact element={<Home />} />
          <Route path='/movie/:imdbID' element={<MovieDetails />} />
          <Route element={<PageNotFound />} />
        </Routes>
        <Footer />
      </BrowserRouter>
    </div>
  );
}

What I want is for PageNotFound to be shown when I enter an invalid url. But it never shows up. I tried putting it at the top, after the <Routes> but same result.

You can add the * to the path and it will render.

function App() {
  return (
    <div className="app">
      <BrowserRouter>
        <Header></Header>
        <Routes>
          <Route path='/' exact element={<Home />} />
          <Route path='/movie/:imdbID' element={<MovieDetails />} />
          <Route exact path='*' element={<PageNotFound />} />
        </Routes>
        <Footer />
      </BrowserRouter>
    </div>
  );
}

Route order doesn't matter in react-router-dom@6 as routes use a route path ranking system now to match the most appropriate path. Routes are now always exactly matched as well, so there's no longer any exact prop.

Route components that match paths still need a path prop. Specify a wildcard "*" path to match anything any of the more specific paths don't.

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

See How dow I add a No Match (404) route in react-router v6

// use it in this way it will work 

function App() {
  return (
    <div className="app">
      <BrowserRouter>
        <Header></Header>

        <Routes>
          <Route   path='*' element={<PageNotFound />} />
          <Route path='/' exact element={<Home />} />
          <Route path='/movie/:imdbID' element={<MovieDetails />} />
         
        </Routes>
        <Footer />
      </BrowserRouter>
    </div>
  );
}

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