showing results for - "react router config private routes"
Lacy
06 Sep 2018
1// renderRoutes.js
2
3import React from 'react'
4import Switch from 'react-router/Switch'
5import { Route, Redirect } from 'react-router-dom'
6
7const renderRoutes = (routes, authed, authPath, extraProps = {}, switchProps = {}) => routes ? (
8  <Switch {...switchProps}>
9    {routes.map((route, i) => (
10      <Route
11        key={route.key || i}
12        path={route.path}
13        exact={route.exact}
14        strict={route.strict}
15        render={(props) => {
16          
17          if( !route.restricted || authed || route.path == authPath) {
18            return <route.component {...props} {...extraProps} route={route}/>
19          }
20          const redirPath = authPath ? authPath : '/login'
21          return <Redirect to={{pathname: redirPath, state: {from: props.location}}}/>
22        }}
23      />
24    ))}
25  </Switch>
26) : null
27
28export default renderRoutes
Carla
26 Feb 2020
1// Login.js
2
3import React from 'react'
4
5class Login extends React.Component {
6   render() {
7      const { from } = this.props.location.state || { from: {pathname: '/' } }
8         return (
9	    <div>
10	       <p>You must log in to view this page at {from.pathname} </p>
11	          <button onClick={this.login}>Log in </button>
12	     </div>
13	 )
14   }
15}
16
17export default Login
Sophia
28 Jul 2016
1// caller of renderRoutes
2
3import React from 'react'
4import { Switch } from 'react-router-dom'
5//import { renderRoutes } from 'react-router-config'
6import renderRoutes from '../renderRoutes'
7import routes from '../routes3'
8
9const authed = false // <-- You can change this
10const authPath = '/login' // <-- You can change this
11
12const Main = () => (
13   <main>
14      <Switch>
15         {renderRoutes(routes, authed, authPath)}
16      </Switch>
17   </main>
18)
19
20export default Main
Antoine
13 Jan 2017
1// routes.js
2import Home from './components/Home'
3import Login from './components/User/Login'
4import User from './components/User/User'
5
6const routes = [
7	{ path: '/',
8		exact: true,
9		restricted: false,  // <-- NEW
10		component: Home,
11	},
12	{
13		path: '/login',
14		restricted: false, // <-- NEW
15		component: Login,
16	},
17	{
18		path: '/user',
19		restricted: true, // <-- NEW
20		component: User,
21	},
22	{
23		path: '*',
24		restricted: false, // <-- NEW
25		component: NotFound
26	}
27]