react-router v6: get path pattern for current route

I made a custom hook useCurrentPath with react-router v6 to get the current path of route, and it work for me

If the current pathname is /members/5566 I will get path /members/:id

import { matchRoutes, useLocation } from "react-router-dom"

const routes = [{ path: "/members/:id" }]

const useCurrentPath = () => {
  const location = useLocation()
  const [{ route }] = matchRoutes(routes, location)

  return route.path
}

function MemberPage() {
  const currentPath = useCurrentPath() // `/members/5566` -> `/members/:id`
   
  return <></>
}

Reference

https://reactrouter.com/en/v6.3.0/api#matchroutes

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)