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.