Пожалуйста, попробуйте следующий код. Вы можете использовать отдельный файл отдельного маршрута
PrivateRoute. js
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
export const PrivateRoute = ({ component: Component, ...rest }) => {
return (
<React.Fragment>
<Route {...rest} render={props => (
localStorage.getItem('token')
? <Component {...props} />
: <Redirect to={{ pathname: '/login'}} />
)} />
</React.Fragment>
)
}
Маршрут. js
import React, { Component } from 'react';
import {Route, Switch} from 'react-router-dom';
import Login from './components/Login/Login'
import { PrivateRoute } from "./PrivateRoute";
import Dashboard from "./components/Home/Dashboard";
import Notfound from './Notfound';
class Routes extends Component {
render() {
return (
<React.Fragment>
<Switch>
<PrivateRoute exact path="/" component={Dashboard} label="Home"/>
<Route path="/login" component={Login} />
<Route path="*" component={Notfound} />
</Switch>
</React.Fragment>
)
}
}
export default Routes;