Pass Component to guard in react

37 Views Asked by At

I am passing the component to the guard in react and for some reason it is show nothing. This Is what i am doing:

<Route path='/dashboard' element={AuthGuard(<Dashboard/>)} />

The Guard:

export default function AuthGuard(ComposedComponent){
 const AuthenticationCheck = (props) => {
        const [isAuth,setIsAuth] = useState(false);
        const users = useSelector(state => state.users);
     const navigate = useNavigate();

        useEffect(() => {
            if(!users.auth){
                navigate('/');
            }else {
                setIsAuth(true);
            }
        },[navigate,props,users]);

        if(!isAuth){
            return (
                <Loader full={true}/>
            )
        }else {
            return (
                <ComposedComponent users={users} {...props}/>
            )
        }
 }
 return AuthenticationCheck;
}

How Can i fix this? it is going to the right place

1

There are 1 best solutions below

2
hamzaouni On

export default function AuthGuard(ComposedComponent) {
  const AuthenticationCheck = (props) => {
    const [isAuth, setIsAuth] = useState(false);
    const users = useSelector(state => state.users);
    const navigate = useNavigate();

    useEffect(() => {
      if (!users.auth) {
        navigate('/');
      } else {
        setIsAuth(true);
      }
    }, [navigate, users]);

    if (!isAuth) {
      return (
        <Loader full={true} />
      );
    } else {
      return (
        <ComposedComponent users={users} {...props} />
      );
    }
  };

  return <AuthenticationCheck />;
}

Now, when you use the AuthGuard, you simply pass the component as an argument without calling it:

<Route path='/dashboard' element={<AuthGuard ComposedComponent={Dashboard} />} />