From 64459540b1fc528e2403af4104a5754cc6d71bce Mon Sep 17 00:00:00 2001 From: Alberto Defendi <1369-ahl-berto@users.noreply.gitlab.inf.unibz.it> Date: Wed, 14 Apr 2021 11:21:20 +0200 Subject: [PATCH] Private route component --- src/App.tsx | 3 +- .../utils/PrivateRoute/PrivateRoute.tsx | 38 +++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 src/components/utils/PrivateRoute/PrivateRoute.tsx diff --git a/src/App.tsx b/src/App.tsx index 9d9a8cf..65acb82 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -3,6 +3,7 @@ import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'; import { HomePage } from 'components/HomePage/HomePage'; import { AuthUser } from 'components/AuthUser/AuthUser'; import { LandingPage } from 'components/LandingPage/LandingPage'; +import { PrivateRoute } from 'components/utils/PrivateRoute/PrivateRoute'; export const App: FC = () => ( <Router> @@ -10,7 +11,7 @@ export const App: FC = () => ( <Switch> <Route path="/auth" component={AuthUser} /> <Route exact path="/" component={LandingPage} /> - <Route exact path="/home" component={HomePage} /> + <PrivateRoute path="/home" Component={HomePage} /> </Switch> </div> </Router> diff --git a/src/components/utils/PrivateRoute/PrivateRoute.tsx b/src/components/utils/PrivateRoute/PrivateRoute.tsx new file mode 100644 index 0000000..9492da9 --- /dev/null +++ b/src/components/utils/PrivateRoute/PrivateRoute.tsx @@ -0,0 +1,38 @@ +import React from 'react'; +import { Route, Redirect, RouteProps } from 'react-router-dom'; + +/** + * A wrapper for <Route> that redirects to the login screen if you're not yet authenticated. + * */ + +type Props = { + Component: React.FC<RouteProps>; + path: string; +}; + +/* eslint-disable react/jsx-props-no-spreading */ +export const PrivateRoute = ({ Component, path }: Props): JSX.Element => { + const isAuthed = false; + const message = 'Please log in to view this page'; + return ( + <Route + exact={false} + path={path} + render={(props: RouteProps) => + isAuthed ? ( + <Component {...props} /> + ) : ( + <Redirect + to={{ + pathname: '/auth', + state: { + message, + requestedPath: path, + }, + }} + /> + ) + } + /> + ); +}; -- GitLab