最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get the last part of the current URL with react router v6? - Stack Overflow

programmeradmin3浏览0评论

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..

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..

Share Improve this question edited Mar 31, 2022 at 23:24 Drew Reese 203k17 gold badges235 silver badges267 bronze badges asked Mar 29, 2022 at 11:58 Codehan25Codehan25 3,01412 gold badges58 silver badges109 bronze badges 1
  • It looks to me that one of useResolvedPath or resolvePath might help you normalize one or the other sides of your comparison. – spender Commented Mar 29, 2022 at 12:06
Add a comment  | 

5 Answers 5

Reset to default 5
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])
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')
import { useMatch } from "react-router-dom";

function MyComponent() {
  const match = useMatch("/:firstRoute/:secondRoute/*");
  const { firstRoute, secondRoute } = match.params;
  const lastRoute = match.params["*"];

  return (
    <div>
      <p>First route: {firstRoute}</p>
      <p>Second route: {secondRoute}</p>
      <p>Last route: {lastRoute}</p>
    </div>
  );
}

You can use the combination of useResolvedPath and useMatch like so:

    const basePath = useResolvedPath('..'); // to get the current path 1 level higher 
    const match = useMatch<'section', string>(`${basePath.pathname}/:section`);
    const lastPartOfTheURL = match.params.section;

发布评论

评论列表(0)

  1. 暂无评论