Answers for "react-router-config private routes"

0

react-router-config private routes

// Login.js

import React from 'react'

class Login extends React.Component {
   render() {
      const { from } = this.props.location.state || { from: {pathname: '/' } }
         return (
	    <div>
	       <p>You must log in to view this page at {from.pathname} </p>
	          <button onClick={this.login}>Log in </button>
	     </div>
	 )
   }
}

export default Login
Posted by: Guest on September-07-2020
0

react-router-config private routes

// caller of renderRoutes

import React from 'react'
import { Switch } from 'react-router-dom'
//import { renderRoutes } from 'react-router-config'
import renderRoutes from '../renderRoutes'
import routes from '../routes3'

const authed = false // <-- You can change this
const authPath = '/login' // <-- You can change this

const Main = () => (
   <main>
      <Switch>
         {renderRoutes(routes, authed, authPath)}
      </Switch>
   </main>
)

export default Main
Posted by: Guest on September-07-2020
0

react-router-config private routes

// routes.js
import Home from './components/Home'
import Login from './components/User/Login'
import User from './components/User/User'

const routes = [
	{ path: '/',
		exact: true,
		restricted: false,  // <-- NEW
		component: Home,
	},
	{
		path: '/login',
		restricted: false, // <-- NEW
		component: Login,
	},
	{
		path: '/user',
		restricted: true, // <-- NEW
		component: User,
	},
	{
		path: '*',
		restricted: false, // <-- NEW
		component: NotFound
	}
]
Posted by: Guest on September-07-2020
0

react-router-config private routes

// renderRoutes.js

import React from 'react'
import Switch from 'react-router/Switch'
import { Route, Redirect } from 'react-router-dom'

const renderRoutes = (routes, authed, authPath, extraProps = {}, switchProps = {}) => routes ? (
  <Switch {...switchProps}>
    {routes.map((route, i) => (
      <Route
        key={route.key || i}
        path={route.path}
        exact={route.exact}
        strict={route.strict}
        render={(props) => {
          
          if( !route.restricted || authed || route.path == authPath) {
            return <route.component {...props} {...extraProps} route={route}/>
          }
          const redirPath = authPath ? authPath : '/login'
          return <Redirect to={{pathname: redirPath, state: {from: props.location}}}/>
        }}
      />
    ))}
  </Switch>
) : null

export default renderRoutes
Posted by: Guest on September-07-2020

Code answers related to "react-router-config private routes"

Code answers related to "Javascript"

Browse Popular Code Answers by Language