Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current url path using hook router in react?

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!

like image 210
Dhruvil21_04 Avatar asked Sep 13 '19 02:09

Dhruvil21_04


2 Answers

I finally found on github doc.

import {usePath} from 'hookrouter';

const PathLabel = () => {
    const path = usePath();
    return <span>Your current location: {path}</span>;
}
like image 53
Dhruvil21_04 Avatar answered Nov 15 '22 18:11

Dhruvil21_04


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>
    );
};
like image 26
AveryFreeman Avatar answered Nov 15 '22 16:11

AveryFreeman