We can consume the Redirect
component from react-router-dom
, in order to redirect a user from the / path
to the /login
:
<Route path="/" render={() =><Redirectto="/login"/>} exact />
We can use this component to Redirect
a user from one page to another, based on certain conditions. One of the situations is, if a user is logged in, we can Redirect
the user to the dashboard page; otherwise, we can ask the user to log in:
import React from "react"; import { Route, Redirect } from "react-router-dom"; const redirect = () => ( <Route exact path="/" render={() => loggedIn ? <Redirect to="/dashboard" /> : <PublicHomePage /> } /> ); export default redirect;
You may be wondering how we can test our Redirect
component. Our test could look as follows:
import React from "react"; import renderer from "react-test-renderer"; import RedirectDemo from "../redirect"; jest.mock("react-router-dom", () => ({ Redirect: "Redirect...