5ecured
5ecured

Reputation: 201

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.

Upvotes: 1

Views: 70

Answers (3)

Drew Reese
Drew Reese

Reputation: 202595

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

Upvotes: 0

AmirYousaf
AmirYousaf

Reputation: 21

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

Upvotes: 0

mgm793
mgm793

Reputation: 2066

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

Upvotes: 2

Related Questions