Home > Back-end >  Functions are not valid as a React child. React-router
Functions are not valid as a React child. React-router

Time:01-10

I am following a course in which a condition is made to know if the user is logged in or not, however I receive an error despite having the same code as in the video.

I am using react-router-dom V6.

This is the code:

const logged = false;

<Route path='/profile' component={ProfilePage}>
  {
   logged ?
     () => {
       (<ProfilePage />)
     }
   : () => {
     alert('You must start session')
     return (<Redirect to='/login' />)
    }
  }
</Route>

Error: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.

CodePudding user response:

If using a nested function, you need to invoke it:

const logged = false;

<Route path='/login' component={ProfilePage}>
   {
     logged ?
       (() => {
         (<ProfilePage/>)
       })();
     :
       (() => {
         alert('You must start session')
         return (<Redirect to='/login'/>)
       })();
   }
</Route>

CodePudding user response:

const logged = false;

<Route path='/login' component={ProfilePage}>
   {
     logged
     ? (() => <ProfilePage/>)()
     : (() => {
       alert('You must start session')
       return (<Redirect to='/login'/>)
     })()
   }
</Route>

CodePudding user response:

As I understand you want to create a guard around your private routes, if I'm right, you can create the following guard:

import { useLocation, Navigate } from 'react-router-dom';
//routes
import { getLoginPageUrl } from '../routingConstants/AppUrls';
//constants
import { isAuthenticated } from '@/js/constants/Helpers';

const PrivateRouteGuard = ({ children }) => {
  const location = useLocation();

  if (isAuthenticated()) {
    return <>{children}</>;
  }

  return <Navigate replace to={getLoginPageUrl()} state={{ from: location }} />;
};

export default PrivateRouteGuard;

And use it as follows:

<Routes>
   <Route
       path='/profile'
       element={<PrivateRouteGuard>
        <ProfilePage />
      </PrivateRouteGuard>}
    />
</Routes>
  • Related