How to get the last part of the current URL with react router v6?

Viewed 2237

How can I get the last part of the current url with react router v6?

For example:

If the current path is https://localhost:4200/example/example-details, then I want to check it like this

const location = useLocation();

if (location.pathname === '/example-details')) {
  // do some stuff here
}

..but this always returns the full path.

It works with location.pathname.includes('/example-details'), but I'm curious if there is a way with the react router, like it is possible with the Angular router..

3 Answers
const match = useMatch('/example/:lastPart')
const value = match?.props.lastPart;
if (!!value) {
    // do some stuff here
}

Using useMatch you can apply a template to your current location and extract some parts as props inside the returning object.

check for

location.pathname.includes('/example-details')
const location = useLocation();
const [pathName, setPathName] = useState(null) ;

useEffect(() => {
    if(location) {
        let tmp = location.pathName.slice(location.pathName.lastIndexOf("/") , location.pathName.length) ;
        setPathName(tmp) ;
    }
}, [location])
Related