0
votes

i created private route in react to make some routes private in my react app

import React from 'react'
import Auth from '../../Authentication/Auth'
import { Redirect, Route } from 'react-router-dom'

     const PrivateRoute = ({ component: Component, role, ...rest }) => (
        <Route {...rest} render={props => {
            const loggedIn = Auth.isAuthenticated;
            if (!loggedIn) {
                // not logged in so redirect to login page with the return url
                return <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
            }


            // check if route is restricted by role
            if (Auth.getUserLevel() !== role) {
                // role not authorised so redirect to home page
                return <Redirect to={{ pathname: '/home'}} />
            }

            // authorised so return component
            return <Component {...props} />
        }} />
    )
    export default PrivateRoute;

and i called it in app.js

import React, { Component } from 'react';
    import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom';
    import  AdminPage  from './Containers/AdminPage/AdminPage'
    import PrivateRoute from './Components/PrivateRoute/PrivateRoute'
    import Login from './Containers/Login'

    class App extends Component {
      cnt=0;
      render() {
        return (
          <Wrapper>

            <NavBar />

            <Router>
              <Switch>
                <Route path="/login">
                  <Login />
                </Route >
                <PrivateRoute path="/AdminPage" Component={AdminPage} role='sm'/>
              </Switch>
            </Router>

          </Wrapper>
        )
      }
    }

    export default App;

and when i try to run the app it gives me this error ×

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

1
You haven't imported Navbar in App.js - Shubham Khatri
Check whether the export style (named or default) of App, Login and AdminPage from their respective files match their import style at where they are required. - Lakshya Thakur
now its working i misspelled component as Component - Ushan Fernando

1 Answers

0
votes

You are accepting component and cast it to Component but your are passing Component as props.

You need to rename the passed prop to be lower case.

<PrivateRoute path="/AdminPage" component={AdminPage} role='sm'/>