Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react router get full current path name

Tags:

Is there an easy way to return the current router address.

IE, if I'm on page, and I just want to see what page I'm on according to the react router.

So, localhost/admin/users would return admin/users

Obviously, I can get the same results by parsing the location, but I was wondering if react router provides a simple mechanism to do this, the same way it provides the params props?

like image 694
l2silver Avatar asked Feb 23 '16 16:02

l2silver


People also ask

What is exact path in React router?

React router does partial matching, so /users partially matches /users/create , so it would incorrectly return the Users route again! The exact param disables the partial matching for a route and makes sure that it only returns the route if the path is an EXACT match to the current url.

How do I get the URL segment in React?

You can use the following: const fullUrl = "http://localhost:3000/register"; //use this to get the complete url => window. location. href; const lastPart = fullUrl.

How do I get the current route name in React?

Use the useLocation() hook to get the current route with React Router, e.g. const location = useLocation() . The hook returns the current location object. For example, you can access the pathname as location. pathname .


1 Answers

If you're using 1.0 or newer, you have the location as a prop in your React components that are matched against a route. So you just type

this.props.location.pathname 

to get what you wanted.

like image 146
Alex Moldovan Avatar answered Jan 03 '23 10:01

Alex Moldovan