Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 351
pyyyyysv Avatar asked Apr 05 '19 00:04

pyyyyysv


2 Answers

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);
like image 65
Alecu Marian Alexandru Avatar answered Oct 19 '22 09:10

Alecu Marian Alexandru


If I understand correctly, you want to extract the path of the current route, while excluding the last userId part of the URL - assuming that's the case, you could do the following:

const getCurrentPathWithoutLastPart = () => {

    return location.pathname.slice(0, location.pathname.lastIndexOf('/'))
}

If your current URL is something like /users/userDetail/some_value calling the function will yield /users/userDetail:

getCurrentPathWithoutLastPart() // returns /users/userDetail
like image 38
Dacre Denny Avatar answered Oct 19 '22 09:10

Dacre Denny