react router dom: redirect and router: all urls are getting redirected, how to stop

Viewed 28

I have the following reactjs code.

I am using react-router-dom V5

import React from "react";
import ReactDOM from "react-dom";
import { createBrowserHistory } from "history";
import { Router, Route, Switch, Redirect } from "react-router-dom";

import Login from "./views/User/Login";
import Signup from "./views/User/SignUp";
import ForgotPassword from "./views/User/ForgotPassword";
import ResetPassword from "./views/User/ResetPassword";

const hist = createBrowserHistory();

ReactDOM.render(
  
    <Router history={hist}>
        <Route path="/signup" component={Signup} />
        <Route path="/login" component={Login} />
        <Route path="/forgot-password" component={ForgotPassword} />
        <Route path="/rest-auth/password/reset/confirm/:uidb64([0-9A-Za-z_\-]+)/:token([0-9A-Za-z]{1,20}-[0-9A-Za-z]{1,50})" component={ResetPassword}/
        <Redirect from="/" to="/login" />
    </Router>,
  document.getElementById("root")
);

Here any url i open in browser it gets redirected to /login

eg: I open /signup it gets redirected to /login

the link works but when i open any url in the browser it gets redirected to /login

1 Answers

I found the reason is not using switch. If i use switch it worked

import React from "react";
import ReactDOM from "react-dom";
import { createBrowserHistory } from "history";
import { Router, Route, Switch, Redirect } from "react-router-dom";

import Login from "./views/User/Login";
import Signup from "./views/User/SignUp";
import ForgotPassword from "./views/User/ForgotPassword";
import ResetPassword from "./views/User/ResetPassword";

const hist = createBrowserHistory();

ReactDOM.render(
  
    <Router history={hist}>
        <Switch>
        <Route path="/signup" component={Signup} />
        <Route path="/login" component={Login} />
        <Route path="/forgot-password" component={ForgotPassword} />
        <Route path="/rest-auth/password/reset/confirm/:uidb64([0-9A-Za-z_\-]+)/:token([0-9A-Za-z]{1,20}-[0-9A-Za-z]{1,50})" component={ResetPassword}/
        <Redirect from="/" to="/login" />
        </Switch>
    </Router>,
  document.getElementById("root")
);

Also Route and Redirect should be directly below the Switch else Switch will not work.

Example

    <Router history={hist}>
        <Switch>
            <>
                <Route path="/signup" component={Signup} />
                <Route path="/login" component={Login} />
                <Route path="/forgot-password" component={ForgotPassword} />
                <Route path="/rest-auth/password/reset/confirm/:uidb64([0-9A-Za-z_\-]+)/:token([0-9A-Za-z]{1,20}-[0-9A-Za-z]{1,50})" component={ResetPassword}/
                <Redirect from="/" to="/login" />
            </>
        </Switch>
    </Router>,

Switch does not have any affect here, so if we try to enter in browser /signup it also matches / so it goes to /login

Related