When the user does not register in the redirection mode to enter the system. Reactjs

My application is as follows:

class App extends Component { render() { <Router> <div> <Route exact path='/login' component={Login} /> <Route exact path='/game' component={GameContainer} /> <Route exact path='/chat' component={ChatContainer} /> <Route exact path='/info' component={InfoContainer} /> </div> </Router> } 

If the user visits the page under the / game and is not logged in, I want to redirect them to the login page.

How to do it in an elegant way on all routers?

+5
source share
1 answer

See this answer fooobar.com/questions/183141 / .... Perhaps someone with more reputation than me might mark this as a duplicate.

The basic idea is to wrap routes that require authentication using a custom component (PrivateRoute in the example below). PrivateRoute will use some logic to determine if the user is authenticated, and then either; allow the requested route for visualization or redirect to the login page.

This is also described in reactive router training documents at this link https://reacttraining.com/react-router/web/example/auth-workflow .

Here is an implementation using the above as inspiration.

In App.js (or where your routing happens)

 import React, { Component } from 'react' import { BrowserRouter as Router, Route } from 'react-router-dom' import PrivateRoute from './PrivateRoute' import MyComponent from '../src/MyComponent' import MyLoginForm from '../src/MyLoginForm' <Router> <Route path="/login" component={MyLoginForm} /> <PrivateRoute path="/onlyAuthorizedAllowedHere/" component={MyComponent} /> </Router> 

And the PrivateRoute component

 // This is used to determine if a user is authenticated and // if they are allowed to visit the page they navigated to. // If they are: they proceed to the page // If not: they are redirected to the login page. import React from 'react' import AuthService from './Services/AuthService' import { Redirect, Route } from 'react-router-dom' const PrivateRoute = ({ component: Component, ...rest }) => { // Add your own authentication on the below line. const isLoggedIn = AuthService.isLoggedIn() return ( <Route {...rest} render={props => isLoggedIn ? ( <Component {...props} /> ) : ( <Redirect to={{ pathname: '/login', state: { from: props.location } }} /> ) } /> ) } export default PrivateRoute 
+8
source

Source: https://habr.com/ru/post/1273633/


All Articles