-1

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.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • There's not enough context here to see what any issue is. Can you [edit] the post to include a more complete [mcve] so readers here can understand what the code is doing overall and why there may be a rendering issue? Can you also include the error message and any stacktrace? It looks like you are trying to protect a route, does this help answer your question? https://stackoverflow.com/questions/66289122/how-to-create-a-protected-route – Drew Reese Jan 09 '23 at 16:21
  • Why are you returning a function instead of the content itself? i.e. why `() => { () }` instead of `()` ? – Wyck Jan 09 '23 at 16:26

3 Answers3

1

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>
xdumaine
  • 10,096
  • 6
  • 62
  • 103
0
const logged = false;

<Route path='/login' component={ProfilePage}>
   {
     logged
     ? (() => <ProfilePage/>)()
     : (() => {
       alert('You must start session')
       return (<Redirect to='/login'/>)
     })()
   }
</Route>
Konrad
  • 21,590
  • 4
  • 28
  • 64
0

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>
Adam Morsi
  • 351
  • 1
  • 7