How to redirect on login with React Router?

Sometimes, we want to redirect on login with React Router.

In this article, we’ll look at how to redirect on login with React Router.

How to redirect on login with React Router?

To redirect on login with React Router, we can render different components depending on the login status.

For instance, we write

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

import Login from "./views/login";
import Supportedmodels from "./views/dashboard/supported-models";

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={(props) =>
      localStorage.getItem("user") ? (
        <Component {...props} />
      ) : (
        <Redirect to={{ pathname: "/login" }} />
      )
    }
  />
);

function App() {
  return (
    <Router>
      <Switch>
        <PrivateRoute path="/" component={Supportedmodels} exact />
        <Route path="/login" component={Login} />
      </Switch>
    </Router>
  );
}

to add the PrivateRoute component that renders a Route component.

We set its render prop to a function that renders Component is the local storage with key user is present.

Otherwise, we render Redirect to redirect to the /login page.

And then we use PrivateRoute in the Switch component to render the Route inside.

Conclusion

To redirect on login with React Router, we can render different components depending on the login status.