Router with Guard — Takeaway routing solution for React project

1. Before react-router-guard

function HomePage(props) {
return (<div> Greeting at my door </div>)
}
import Loadable from ‘react-loadable’;
import Loading from ‘./my-loading-component’;
const HomePageComponent = Loadable({
loader: () => import(‘./HomePage’),
loading: Loading,
});
class App extends Component {
render() {
<Router>
<Route exact path=”/” component={HomePageComponent} />
</Router>
}
}
// get the user's credential from local storage 
import { getUserProfile } from 'utils';
function checkAuth(
FallbackComponent,
...rest,
) {
const profile = getUserProfile();
if (!profile) {
return FallbackComponent
? <FallbackComponent {…rest} />
: <Redirect to="/" />
}
}
export default checkAuth();
import CheckAuth from 'guards/checkAuth';
const ProfilePage = Loadable({
loaded: () => import ('./ProfilePage'),
loading: Loading,
});
const ProfilePageFallback =
class App extends React.Component {
render() {

<Route exact path='/profile' component={ProfilePageFallback}/>

}
}

2. The library we need and the library we deserve

import { dynamicWrapper } from 'react-router-guard';
import { checkAuth } from "./guard";
export default [
{
path: '/',
component: dynamicWrapper(() => import ('./HomePage')),
},
{
canActivate: checkAuth,
path: '/',
component: dynamicWrapper(() => import ('./ProfilePage')),
},{
canActivate: checkNotAuth,
path: '/',
component: dynamicWrapper(() => import ('./SignInPage')),
}
]
import {BrowserRouter} from 'react-router-dom';
import RouterGuard from ‘react-router-guard’;
function App() {
return (
<BrowserRouter>
<RouterGuard config={config} />
</BrowserRouter>
)
}
  • Default or customized loading UI component on unfinished routing
  • Template for nested route
  • Dynamic redirect with parameters

--

--

Người Việt Nam sống trên Internet là chủ yếu

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Phạm Huy Phát

Phạm Huy Phát

Người Việt Nam sống trên Internet là chủ yếu