Reputation: 31
I am trying to create a protected route as shown in the code below:
const PrivateRoute = ({component:Component, authenticated, ...rest}) =>{
console.log(authenticated);
return(
<Route {...rest} render={(props) => (
authenticated === true
? <Component {...props} {...rest} />
: <Redirect to="/Login"/>
)} />);
}
export default PrivateRoute;
I am passing the following params in my Router configuration:
<PrivateRoute component={Appointments} authenticated={this.state.authenticated} exact path="/appointments" render={(props) => <Appointments {...props} appointments={this.state.appointments} />} />
.
However, when I try routing, it appears that the "appointments={this.state.appointments}" prop is not getting passed to the "Appointments" component.
This is the error that I get
TypeError: Cannot read property 'map' of undefined
Any idea what the issue could be?
Upvotes: 1
Views: 1705
Reputation: 2731
function PrivateRoute({ children, ...rest }) {
const isAuthenticated = (location) => {
//if loading show loading indicator
}
const childrenWithLocation = (location) => Children.map(children, child => {
if (isValidElement(child)) {
return cloneElement(child, { to: child.props?.to + location.search });
}
return child;
});
return (
<Route
{...rest}
render={({ location }) =>
isAuthenticated(location)
? (childrenWithLocation(location))
: (<Redirect
to={{
pathname: "/login" + location.search,
state: { from: location }
}}
/>)
}
/>
);
}
Upvotes: 0
Reputation: 1882
I think the problem here is that you are passing props in the render property of the PrivateRoute
which is as render={(props) => <Appointments {...props} appointments={this.state.appointments} />}
. Now this property is not being Utilised in your actual component rendering in the PrivateRoute
. Try following during your initialisation of route:
<PrivateRoute component={Appointments} authenticated={this.state.authenticated} exact path="/appointments" appointments={this.state.appointments} />
This should fix your issue. I would suggest here that rather than creating a PrivateRoute of your own, you can use a React HOC to create an authentication wrapper on the actual component.
Upvotes: 1