I'm new to react and react hooks. I'm using hookrouter package and I tried to googling about the question, but didn't find much about it.
What I want?
I'm trying to get the current url path. For e.g. for https://example.com/users/temp
, I want to get /users/temp
.
Any help will be appreciated. Thanks in advance!
I finally found on github doc.
import {usePath} from 'hookrouter';
const PathLabel = () => {
const path = usePath();
return <span>Your current location: {path}</span>;
}
I wanted to let you know there's also a generic way to return the path using Javascript, in case you're not using hookrouter on a different project
Just invoke window.location.pathname
I'm using it for setting active className for links in my Nav component based on which route the client is on using a ternary expression. Example:
const NavList = props => {
return (
<NavContainer>
<ul>
{routes.map(({ key, href, label }) => (
<A href={href} key={key} className='route-link'>
<li
className={href === window.location.pathname ? 'active' : null}
>
{label}
</li>
</A>
))}
</ul>
</NavContainer>
);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With