0

I am trying to create a conditional route by creating a ProtectedRoute component as described by the chosen answer of this question.

The condition comes from the props passed into the ProtectedRoute component. Please have a look at the component and routing code below.

import React, {Component} from "react";
import { Route } from 'react-router-dom';
import { Redirect } from 'react-router';

class ProtectedRoute extends Component {
    render() {
      const { component: Component, ...props } = this.props
  
      return (
        <Route 
          {...props} 
          render={props => (
            this.props.profile.name === "admin" ?
              <Component {...props} /> :
              <Redirect to='/login' />
          )} 
        />
      )
    }
  }
export default ProtectedRoute;

The following is how I achieve the routing in a separate side navigation bar component. The profile object is passed as props to this component from App.js.

<main>
      <Route path="/" exact component={props => <Home/>} />
      <ProtectedRoute path="/dashboard" component={props => <Dashboard profile={this.props.profile} />} />
</main>

The error I am getting when running the above application is: TypeError: _this2.props.pofile is undefined. However, when I put a Route instead of ProtectedRoute i.e.
<Route path="/dashboard" component={props => <Dashboard profile={this.props.profile} />} />,
the application works as expected.

Could someone please assist me by pointing out what I am doing wrong? That would be much appreciated.

Community
  • 1
  • 1
craig-nerd
  • 569
  • 1
  • 6
  • 22

3 Answers3

1

Inside Route's render property you use an arrow function which means that context inside it is bound to ProtectedRoute's instance. this.props inside render resolve to props of ProtectedRoute in other words. To solve this issue you need to pass profile to ProtectedRoute instead of Dashboard:

<main>
  <Route path="/" exact component={props => <Home/>} />
  <ProtectedRoute path="/dashboard" profile={this.props.profile} component={props => <Dashboard />} />
</main>
Volodymyr
  • 1,190
  • 1
  • 4
  • 11
0

On this error TypeError: _this2.props.pofile is undefined it's pofile and not profile

Some where you define the wrong typo maybe.

hydrog3n
  • 38
  • 6
0

The reason why _this2.props.pofile is undefined - you haven't passed it to ProtectedRoute component, however, you passed it to Dashboard.

The right way to pass it is:

<ProtectedRoute path="/dashboard" profile={this.props.profile} component={props => <Dashboard profile={this.props.profile} />} />

By the way, it is not the best practice to pass JSX as a prop, better to pass it as children:

<ProtectedRoute path="/dashboard" profile={this.props.profile}>
  <Dashboard profile={this.props.profile} />
</ProtectedRoute>

and then inside of ProtectedRoute just render {this.props.children}.

Igor Buts
  • 57
  • 6