React-Router-dom Redirect is not respecting the exact attribute

Viewed 587

My issue is when trying to redirect the particular url to another url, it by default redirect all the url to the given redirected path. I just want to redirect for a certain path for ex

 <Redirect exact from="/" to="/movies"></Redirect>

I just want to redirect http://localhost:3000/ t0 http://localhost:3000/movies, which is working fine but now if i visit http://localhost:3000/xyz it again redirect me to http://localhost:3000/movies

codesandbox https://codesandbox.io/s/frosty-joliot-zbkf9?file=/src/App.js

2 Answers

Instead do :

<Route exact path="/">
    <Redirect to="/movies" />
</Route>

Redirect from prop

Note: This can only be used to match a location when rendering a <Redirect> inside of a <Switch>. See <Switch children> for more details.

You need to wrap your routes and redirect in a Switch in order for the from prop to function, and not specify an earlier matching path to that of what you want to redirect from, i.e. "/".

import { BrowserRouter, Switch, Route, Redirect } from "react-router-dom";

export default function App() {
  return (
    <BrowserRouter>
      <main className="container">
        <Switch>
          <Route exact path="/movies" />
          <Route exact path="/test" />
          <Redirect exact from="/" to="/movies" />
        </Switch>
      </main>
    </BrowserRouter>
  );
}

Edit react-router-dom-redirect-is-not-respecting-the-exact-attribute

This demo has 3 links, a link to home ("/") which will match the Redirect, a link to test ("/test") which will match, and a link to notTest ("/notTest") that won't match any routes. Any other paths also won't be matched by the Switch.

Note: a common pattern is to not match any route for the redirect and leave it to simply be a "catch-all" path that can redirect to a known/handled path in your app/router.

Related