Skip to content

Instantly share code, notes, and snippets.

@niikkiin
Created June 24, 2020 16:28
Show Gist options
  • Save niikkiin/c092776c18888e193026fb212e48929e to your computer and use it in GitHub Desktop.
Save niikkiin/c092776c18888e193026fb212e48929e to your computer and use it in GitHub Desktop.
PrivateRoute setup in ReactJs
import React, { Suspense, useEffect } from 'react';
// routing
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import PrivateRoute from 'routing/private-route.routing';
// global styles
import { GlobalStyles } from 'utilities/styles/global.styles';
// redux
import { Provider } from 'react-redux';
import store from 'store/store';
import { loadUser } from 'store/actions/auth.actions';
import setAuthToken from 'utilities/auth/set-auth-token.utilities';
const SignInPage = React.lazy(() => import('pages/auth/sign-in-page.component'));
const SignUpPage = React.lazy(() => import('pages/auth/sign-up-page.component'));
const DashboardPage = React.lazy(() => import('pages/dashboard/dashboard.component'));
if(localStorage.token) {
setAuthToken(localStorage.token);
}
const App = () => {
useEffect(() => {
store.dispatch(loadUser());
}, []);
return (
<Provider store={store}>
<Router>
<GlobalStyles />
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route exact path='/' component={SignInPage} />
<Route exact path='/register' component={SignUpPage} />
<PrivateRoute exact path='/dashboard' component={DashboardPage} />
</Switch>
</Suspense>
</Router>
</Provider>
);
}
export default App;
import React from 'react';
// proptypes
import PropTypes from 'prop-types';
// redux
import { connect } from 'react-redux';
// router
import { Route, Redirect } from 'react-router-dom';
const PrivateRoute = ({ component: Component, auth: { isAuthenticated, loading }, ...rest }) => (
<Route
{...rest}
render={(props) => (!isAuthenticated && !loading ? <Redirect to='/' /> : <Component {...props} />)}
/>
);
PrivateRoute.propTypes = {
auth: PropTypes.object.isRequired,
};
const mapStateToProps = (state) => ({
auth: state.auth,
});
export default connect(mapStateToProps)(PrivateRoute);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment