Skip to content

Instantly share code, notes, and snippets.

@junieldantas
Forked from alanfoandrade/(routes)Route.tsx
Created October 22, 2020 01:59
Show Gist options
  • Save junieldantas/9795a5f7372fc734fb7f92f73dd3955d to your computer and use it in GitHub Desktop.
Save junieldantas/9795a5f7372fc734fb7f92f73dd3955d to your computer and use it in GitHub Desktop.
import React from 'react';
import { Switch } from 'react-router-dom';
import Route from './Route';
import SignIn from '../pages/SignIn';
import SignUp from '../pages/SignUp';
import ForgotPassword from '../pages/ForgotPassword';
import ResetPassword from '../pages/ResetPassword';
import Profile from '../pages/Profile';
import Dashboard from '../pages/Dashboard';
const Routes: React.FC = () => (
<Switch>
<Route path="/" exact component={SignIn} />
<Route path="/signup" component={SignUp} />
<Route path="/forgot-password" component={ForgotPassword} />
<Route path="/reset-password" component={ResetPassword} />
<Route path="/profile" component={Profile} isPrivate />
<Route path="/dashboard" component={Dashboard} isPrivate />
</Switch>
);
export default Routes;
import React from 'react';
import {
Route as ReactDOMRoute,
RouteProps as ReactDOMRouteProps,
Redirect,
} from 'react-router-dom';
import { useAuth } from '../hooks/auth';
interface IRouteProps extends ReactDOMRouteProps {
isPrivate?: boolean;
component: React.ComponentType;
}
const Route: React.FC<IRouteProps> = ({
isPrivate = false,
component: Component,
...rest
}) => {
const { user } = useAuth();
return (
<ReactDOMRoute
{...rest}
render={({ location }) => {
return isPrivate === !!user ? (
<Component />
) : (
<Redirect
to={{
pathname: isPrivate ? '/' : '/dashboard',
state: { from: location },
}}
/>
);
}}
/>
);
};
export default Route;
import React from 'react';
import { BrowserRouter as Router } from 'react-router-dom';
import GlobalStyle from './styles/global';
import AppProvider from './hooks';
import Routes from './routes';
const App: React.FC = () => (
<Router>
<AppProvider>
<Routes />
</AppProvider>
<GlobalStyle />
</Router>
);
export default App;
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root'),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment