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!

2 Answers 2

6

I finally found on github doc.

import {usePath} from 'hookrouter';

const PathLabel = () => {
    const path = usePath();
    return <span>Your current location: {path}</span>;
}
Sign up to request clarification or add additional context in comments.

Comments

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>
    );
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.