Home > Software engineering >  React router dom is not rendering a component
React router dom is not rendering a component

Time:09-14

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.

CodePudding user response:

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>
  );
}

CodePudding user response:

// 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>
  );
}

CodePudding user response:

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

  • Related