Conditional redirect

We can use the Redirect component to protect pages from unauthorized users. In our shop, we can use this to ensure only logged in users can access our Admin page. We do this through the following steps:

  1. Let's start by adding a route to a LoginPage in Routes.tsx after the route to the Admin page:
<Route path="/login" component={LoginPage} />
  1. Of course, LoginPage doesn't exist at the moment, so, let's create a file called LoginPage.tsx and enter the following:
import * as React from "react";

const LoginPage: React.SFC = () => {
return (
<div className="page-container">
<h1>Login</h1>
<p>You need to login ...</p>
</div>
);
};

export default LoginPage;
  1. We can then go back to Routes.tsx and import LoginPage:
import LoginPage from "./LoginPage";
  1. If we go to the running app and navigate to "/login", we will see our Login page:

We are not going to fully implement our Login page; the page that we have implemented is enough to demonstrate a conditional redirect.

  1. Before we implement the conditional redirect on the "admin" path, we need to add a piece of state for whether a user is logged in or not in Routes.tsx:
const Routes: React.SFC = () => {
const [loggedIn, setLoggedIn] = React.useState(false);
return (
<Router>
...
</Router>
);
};

So, we have used a useState hook to add a state variable called loggedIn and a function to set it called setLoggedIn.

  1. The final step is to add the following inside the Route component with the "/admin" path:
<Route path="/admin">
{loggedIn ? <AdminPage /> : <Redirect to="/login"
/>}
</Route>
We conditionally render AdminPage if the user is logged in, otherwise, we redirect to the "/login" path. If we now click the admin link in our running app, we get redirected to the Login page.
  1. If we change the loggedIn state to be true when we initialize it, we are able to access our Admin page again:
const [loggedIn, setLoggedIn] = React.useState(true);
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.209.131