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.