Home > Net >  Why I am unable to navigate using Navigate component?
Why I am unable to navigate using Navigate component?

Time:01-16

I am trying to make a helper function that takes the location string as a parameter and then navigates.

const HandleNavigation = ({location}) => { 
    return <Navigate to={location} replace />;
};

<button onClick={()=><HandleNavigation location='/home'/>} > Click me </button>

Please guide me why this approach to navigate does not work.

CodePudding user response:

One possible solution would be this:

import { useNavigate } from "@reach/router"

const HandleNavigation = ({location}) => { 
    const navigate = useNavigate();
    return <button onClick={() => navigate(location, {replace: true})} > Click me </button>;
};

CodePudding user response:

For this application, you have to use useNavigate.
The Navigate component only can be treated as a component, not a function.

Like this:

const AuthReq = ({isAuth}) => {
    if(isAuth) return <Navigate to="/login" />
    
    return // something else
}

And for your application it would be like this:

const navigate = useNavigate();

return <button onClick={() => navigate(location, { replace: true })}>Title</button>
  • Related