5

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!

Linda Paiste
  • 38,446
  • 6
  • 64
  • 102
Dhruvil21_04
  • 1,804
  • 2
  • 17
  • 31

2 Answers2

6

I finally found on github doc.

import {usePath} from 'hookrouter';

const PathLabel = () => {
    const path = usePath();
    return <span>Your current location: {path}</span>;
}
Dhruvil21_04
  • 1,804
  • 2
  • 17
  • 31
4

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>
    );
};
AveryFreeman
  • 1,061
  • 2
  • 14
  • 23