'how get react router origin url without params?
I want to origin url path without router params.
// routers
<Route
exact
path={`/users/userDetail/:userId`}
component={UserDetail}
/>
i want to get string "/users/userDetail" from some components
help me!
Solution 1:[1]
You can exclude all params from current pathname by using this hook:
import { useLocation, useParams } from 'react-router-dom';
export const useBasePath = () => {
const location = useLocation();
const params = useParams<Record<string, string>>();
return Object.values(params).reduce(
(path, param) => path.replace('/' + param, ''),
location.pathname,
);
};
Use it like this in your component:
const basePath = useBasePath();
console.log(basePath);
Solution 2:[2]
The existing solution is helpful, but it doesn't work for all scenarios. For example, we can't use it for the parent pathname as it will return empty string.
Adding to the existing solution:
const getCurrentPathWithoutLastPart = () => {
const pathRgx = /\//g;
const childroutecount = ((location.pathname || '').match(pathRgx) || []).length
return childroutecount > 1 ? location.pathname.slice(0, location.pathname.lastIndexOf('/')) : location.pathname;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alecu Marian Alexandru |
| Solution 2 | Elletlar |
