I'm creating a webapp in react js and following this tutorials: https://www.youtube.com/watch?v=PKwu15ldZ7k&t=2002s can someone explain this piece of code to me.
return currentUser ? <Outlet /> : <Navigate to="/login" />;
I understand that if currentUser is null then it redirects to login. Is there a way to make it return a different page if not null?
This is basically a one-liner if statement. It reads:
if (currentUser) { // If currentUser is different than undefined/null/false
return <Outlet />
} else {
return <Navigate to="/login" />
}
As this point, you can choose to return anything you want in either case. You could redirect to any page you have, you could return any other components, etc.
This piece of code return currentUser ? <Outlet /> : <Navigate to="/login" />; is called a ternary operator. In other words, if currentUser is true then return the Outlet component otherwise return the Navigate component. It is a shortened way to write an if/else statement.
Here is more on ternary operators: MDN Web Docs: ternary operator
If you want it to redirect to a different url when it returns the Navigate component then you simply changed the /login to whatever url you want to load on null /someOtherURL