Rotas Privadas

Configuração de Rotas

Arquivo src/routes/Route.js

import React from 'react';
import PropTypes from 'prop-types';
import { Route, Redirect } from 'react-router-dom';
export default function RouteWrapper({
component: Component,
isPrivate,
...rest
}) {
const signed = false;
if (!signed && isPrivate) {
return <Redirect to="/" />;
}
if (signed && !isPrivate) {
return <Redirect to="/" />;
}
return <Route {...rest} component={Component} />;
}
RouteWrapper.propTypes = {
isPrivate: PropTypes.bool,
component: PropTypes.oneOfType([PropTypes.element, PropTypes.func])
.isRequired,
};
RouteWrapper.defaultProps = {
isPrivate: false,
};

Arquivo routes/index.js

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 Dashboard from '../pages/Dashboard';
import Profile from '../pages/Profile';
export default function Routes() {
return (
<Switch>
<Route path="/" exact component={SignIn} />
<Route path="/register" component={SignUp} />
<Route path="/dashboard" component={Dashboard} isPrivate />
<Route path="/profile" component={Profile} isPrivate />
</Switch>
);
}

Layouts Padrões

No exemplo abaixo existem dois layouts, um para autenticação (login e cadastro em src/pages/_layouts/auth/index.js), e outra para o restante da aplicação (em src/pages/_layouts/default/index.js).

Arquivo src/routes/Route.js

// ...
import PropTypes from 'prop-types';
// ...
// Importação dos Layouts
import AuthLayout from '../pages/_layouts/auth';
import DefaultLayout from '../pages/_layouts/default';
export default function RouteWrapper({
component: Component,
isPrivate,
...rest
}) {
const signed = false;
if (!signed && isPrivate) {
return <Redirect to="/" />;
}
if (signed && !isPrivate) {
return <Redirect to="/dashboard" />;
}
const Layout = signed ? DefaultLayout : AuthLayout;
// Condicional para definir qual layout será renderizado
return (
<Route
{...rest} // Propriedades do componente de rota
render={props => ( // Renderiza todas as propriedades
<Layout> {/* Renderiza o Layout definido anteriormente */}
<Component {...props} {/* Renderiza o componente e suas propriedades */} />
</Layout>
)}
/>
);
}
RouteWrapper.propTypes = {
isPrivate: PropTypes.bool,
component: PropTypes.oneOfType([PropTypes.element, PropTypes.func])
.isRequired,
};
RouteWrapper.defaultProps = {
isPrivate: false,
};