Skip to content

Instantly share code, notes, and snippets.

@gkueny gkueny/index-edited.js
Last active May 14, 2017

Embed
What would you like to do?
Extrait de codes, pour l'article http://frenchreact.fr/proteger-son-application/
<Router>
<AppComponent>
<Route exact path="/" component={HomeComponent} />
<Route path="/login" component={LoginComponent} />
<ProtectedRoute path="/admin" component={AdminComponent} />
</AppComponent>
</Router>
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import AppComponent from './components/app.component';
import HomeComponent from './components/home.component';
import AdminComponent from './components/admin.component';
import LoginComponent from './components/login.component';
import * as firebase from 'firebase';
import { config } from './vars/firebase.config';
import './assets/css/index.css';
firebase.initializeApp(config);
ReactDOM.render(
<Router>
<AppComponent>
<Route exact path="/" component={HomeComponent} />
<Route path="/admin" component={AdminComponent} />
<Route path="/login" component={LoginComponent} />
</AppComponent>
</Router>,
document.getElementById('root'),
);
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Route, Redirect } from 'react-router-dom';
import { checkUserStatus } from '../services/user.service';
class ProtectedRoute extends Component {
constructor() {
super();
this.state = {
isLogIn: null,
};
}
componentDidMount() {
//On check le statut de l'utilisateur auprès du serveur, et on agit en conséquance
checkUserStatus().then(this.updateUserStatus);
}
//Sera appelé lorsque l'on changera de route
componentWillReceiveProps(nextProps) {
this.state = {
isLogIn: null,
};
//On fait également cette vérification lors d'un changement
checkUserStatus().then(this.updateUserStatus);
}
updateUserStatus = isLogIn => {
if (this.state.isLogIn !== isLogIn) {
this.setState({
isLogIn,
});
}
};
render() {
const { component: Component, ...rest } = this.props;
return (
<Route
{...rest}
render={props => {
if (this.state.isLogIn) {
return <Component {...props} />;
} else if (this.state.isLogIn !== null) {
return <Redirect to={'login'} />;
} else {
return null;
}
}}
/>
);
}
}
ProtectedRoute.propTypes = {
component: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
location: PropTypes.object,
};
export default ProtectedRoute;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.