Home > database >  Get React Router URL
Get React Router URL

Time:06-05

I am trying to write a function that sets the current location to the route that was just clicked. However, as you can see, it gives me the url of the page I was on WHEN I clicked the button, not the page of path of the button itself. What should I use instead of window.location.pathname?

 const setLocation = () => {
    console.log(window.location.pathname);
    setCurrentLocation(window.location.pathname);
  };

 <Link onClick={() => setLocation()} to="/today" className="btn btn-primary btn-sm">

    <Link onClick={() => setLocation()} to="/upcoming" className="btn btn-primary btn-sm">

CodePudding user response:

Why are you storing this to the state ?

ReactRouter has a hook useLocation https://v5.reactrouter.com/web/api/Hooks/uselocation in which you can take .pathname of any pushed path to history.

If you really want to store location by yourself pass on the route value in to as a param in setLocation function or create a component that wraps the Link component and does store location : )

ie:

<Link onClick={() => setLocation("/upcoming")} to="/upcoming" className="btn btn-primary btn-sm">

CodePudding user response:

code is like ===>

onClick={
(e)=>console.log(e.target.href)
setLocation(e.target.href)
}
const setLocation = (path) => {
    console.log(window.location.pathname);
    setCurrentLocation(window.location.pathname path);
  };
  • Related