Tuesday, 25 April 2017

How to protect one admin page with react-router-dom v4?

I'm creating a website with different pages. It uses React.js in the front-end and Express in the back-end. Basically it is a MERN-stack.

For navigation i use react-router-dom v4. Routing works like a charm. Now i have to protect one page. I've tried with the reacttraining.com documentation, but without succes.

My App.js:

import React from 'react';
import { BrowserRouter as Router, Route, Switch, Redirect } from 
'react-router-dom';
import createBrowserHistory from 'history/createBrowserHistory';

const history = createBrowserHistory();

import Home from './Home.jsx';
import Intro from './IntroVideo.jsx';
import Question from './Question.jsx';
import FormPage from './FormPage.jsx';
import Dashboard from './AdminPage.jsx'
import Login from './Login.jsx'
import NotFound from './NotFound.jsx'

 export default class App extends React.Component{
   constructor() {
     super();
     this.state = {
       redirectTo: null
     }
     this.checkAuth = this.checkAuth.bind(this);
   }
   checkAuth(){
     this.setState({
       redirectTo: '/login'
     });
   }
   render() {
     return (
       <Router history={history}>
    <Switch>
      <Route exact path="/" component={Home}/>
      <Route exact path="/intro" component={Intro}/>
      <Route exact path="/question" component={Question}/>
      <Route exact path="/form" component={FormPage} />
      <Route exact path="/dashboard" component={Dashboard} onEnter=
{this.checkAuth} />
      <Route exact path="/login" component={Login} />
      <Route component={NotFound} />
    </Switch>
  </Router>
     )
   }
 }

What is the correct solution for my problem? '/dashboard' needs to be protected and only be seen if you are logged in.

Thx for the help;)



via Thomas Vanhoutte

No comments:

Post a Comment