Skip to content
Snippets Groups Projects
Verified Commit 64459540 authored by Defendi Alberto's avatar Defendi Alberto
Browse files

Private route component

parent 40380a73
No related branches found
No related tags found
1 merge request!23Private route
...@@ -3,6 +3,7 @@ import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'; ...@@ -3,6 +3,7 @@ import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import { HomePage } from 'components/HomePage/HomePage'; import { HomePage } from 'components/HomePage/HomePage';
import { AuthUser } from 'components/AuthUser/AuthUser'; import { AuthUser } from 'components/AuthUser/AuthUser';
import { LandingPage } from 'components/LandingPage/LandingPage'; import { LandingPage } from 'components/LandingPage/LandingPage';
import { PrivateRoute } from 'components/utils/PrivateRoute/PrivateRoute';
export const App: FC = () => ( export const App: FC = () => (
<Router> <Router>
...@@ -10,7 +11,7 @@ export const App: FC = () => ( ...@@ -10,7 +11,7 @@ export const App: FC = () => (
<Switch> <Switch>
<Route path="/auth" component={AuthUser} /> <Route path="/auth" component={AuthUser} />
<Route exact path="/" component={LandingPage} /> <Route exact path="/" component={LandingPage} />
<Route exact path="/home" component={HomePage} /> <PrivateRoute path="/home" Component={HomePage} />
</Switch> </Switch>
</div> </div>
</Router> </Router>
......
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,
},
}}
/>
)
}
/>
);
};
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment