0

I would like to have a universal component that gets called every time I navigate to routes. The main purpose of this component is authentication. To better illustrate what I need I have this example if vue.js:

const routes = [
    { path: '/', component: Login, meta: { auth: false } },
    { path: '/dashboard', component: Dashboard, meta: { auth: true } },
];

router.beforeEach((to, from, next) => {
    if( to.meta.auth ) {
       // run auth, then next();
    } else {
       next();
    }
})

I can I achieve smth like this in ReactJs?

2 Answers 2

1

On the documentation of react-router (assuming you are going to use this router library) there is an example of how to implement authenticated routes: https://reacttraining.com/react-router/web/example/auth-workflow

Using your example you could implement it like this

import React, { Component } from 'react';
import { BrowserRouter, Route, Switch, Redirect } from 'react-router-dom';

import Login from './Login';
import Dashboard from './Dashboard';

const routes = [
  { path: '/', component: (props) => <Login {...props} />, meta: { auth: false } },
  { path: '/dashboard', component: (props) => <Dashboard {...props} />, meta: { auth: true } },
];

export default class MyRouter extends Component {

  isLoggedin() {
    // run auth check that will return true/false 
    return true;
  }

  render() {
    // if loggedin => render component, if not => redirect to the login page
    const PrivateRoute = ({ component: RouteComponent, ...rest }) => (
      <Route
        {...rest}
        render={props => (
        this.isLoggedin() ? (
          <RouteComponent {...props} />
        ) : (
          <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
        )
      )}
      />
    );

    return (
      <BrowserRouter>
        <Switch>
          {routes.map((route, index) => (
            route.meta.auth ?
              <PrivateRoute key={index} path={route.path} exact component={route.component} />
            :
              <Route key={index} path={route.path} exact component={route.component} />
          ))}
        </Switch>
      </BrowserRouter>
    );
  }
}

Inside the PrivateRoute we will check the auth status with this.isLoggedIn() and based on the returned boolean, the component or a Redirect (to the login page for example) is rendered.

Sign up to request clarification or add additional context in comments.

2 Comments

Can I make an ajax call to define if its true or false?
Sure, inside isLoggedin() you can return a fetch Promise (developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) and check the response inside the PrivateRoute: this.isLoggedin().then((response) => { // return <RouteComponent ... /> or <Redirect ... /> }
1

You can create react component that contains login logic. This component wraps all of the routes that require authenticated users. Check this article for solution.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.