Last active
March 4, 2019 08:00
-
-
Save behnammodi/427c2ad3745a2d8d09e6b2bbffd384d5 to your computer and use it in GitHub Desktop.
Sample guard router for react
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from "react"; | |
import { | |
BrowserRouter, | |
Route, | |
Switch, | |
Link, | |
Redirect, | |
withRouter | |
} from "react-router-dom"; | |
const userSigned = true; | |
const routes = [ | |
{ | |
title: "", | |
path: "/login", | |
exact: true, | |
component: () => <div>Login Page</div>, | |
guard: 1, | |
drawer: false | |
}, | |
{ | |
title: "", | |
path: "/", | |
exact: true, | |
component: () => <div>Dashboard Page</div>, | |
guard: 2, | |
drawer: true | |
}, | |
{ | |
title: "", | |
path: "/about", | |
exact: true, | |
component: () => <div>About Page</div>, | |
guard: 3, | |
drawer: false | |
} | |
]; | |
function GuradRoute(props) { | |
switch (props.guard) { | |
case 1: { | |
if (userSigned) return <Redirect to="/" />; | |
else return <Route {...props} />; | |
} | |
case 2: { | |
if (userSigned) return <Route {...props} />; | |
else return <Redirect to="/login" />; | |
} | |
default: { | |
return <Route {...props} />; | |
} | |
} | |
} | |
function Router(props) { | |
const { routes } = props; | |
return ( | |
<Switch> | |
{routes.map(route => ( | |
<GuradRoute | |
key={route.path} | |
exact={route.exact} | |
path={route.path} | |
component={route.component} | |
{...props} | |
{...route} | |
/> | |
))} | |
</Switch> | |
); | |
} | |
const Drawer = withRouter(props => { | |
const route = routes.find(route => route.path === props.location.pathname); | |
return route && route.drawer && <div>Drawer</div>; | |
}); | |
class App extends Component { | |
render() { | |
return ( | |
<BrowserRouter> | |
<> | |
<Router routes={routes} /> | |
<ul> | |
<li> | |
<Link to="/login">Login</Link> | |
</li> | |
<li> | |
<Link to="/">Dashboard</Link> | |
</li> | |
<li> | |
<Link to="/about">About</Link> | |
</li> | |
</ul> | |
<Drawer /> | |
</> | |
</BrowserRouter> | |
); | |
} | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment