I have created a HOC "ProtectedRoute" to restrict paths for unauthenticated users. I have used "react-router-dom" for routing in the application.
I am able to route the users based on their token but I am receiving a warning in the console and I am unable to access routerprops such as "history", "location", "match" in rendered component. Below is the ProtectedRoute component implementation.
const ProtectedRoute = ({component:Component, ...rest}) => {
const [isLoggedIn, setLoggedIn] = useState({loggedIn:false, loaded:false})
useEffect(async () => {
const userStatus = await validateUserLoggedIn(); # returns true if user is authenticated
setLoggedIn((prevState) => {return {loggedIn:userStatus, loaded:true}})
}, [])
return(
<Route {...rest} render={(routerProps) => {
return isLoggedIn.loaded ?
isLoggedIn.loggedIn ? <Component {...routerProps} {...rest} /> : <Redirect to={{pathname:'/login'}} :
<h1>Loading Page</h1>
}} />
)
}
ProtectedRoute in main routing component:
<Switch>
<ProtectedRoute exact path="/admin" component={Admin} />
</Switch>
Error Message "Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it".
Any suggestion is appreciated.
Ok so there a few things wrong.
You should not return something inside a component, you are doing this inside your <Route /> component. This is causing the warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render.
Your <Redirect /> component was missing a /> at the end of it, leaving it open will cause an error.
These fixes should also solve your problem where you couldn't access the route props.
<Route
{...rest}
render={(routerProps) => {
isLoggedIn.loaded ? (
isLoggedIn.loggedIn ? (
<Component {...routerProps} {...rest} />
) : (
<Redirect to={{ pathname: '/login' }} />
)
) : (
<h1>Loading Page</h1>
);
}}
/>;