Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

300
Views
react-router v6: obtenga el patrón de ruta para la ruta actual

¿Es posible obtener el patrón de ruta para la ruta actualmente coincidente? Ejemplo:

 <Route path=":state/:city*" element={ <Page /> } />
 // Page.jsx function Page() { ... // usePathPattern doesn't actually exist const pathPattern = usePathPattern(); // pathPattern = ":state/:city*" ... }

Sé que puedo usar useMatch para verificar si la ubicación actual coincide con un patrón de ruta específico, pero luego el componente debe saber cuál es el patrón de ruta.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Desde dentro del contexto de una Route , puede obtener la path a través de varios métodos establecidos en los documentos .

Mi problema fue ligeramente diferente en el sentido de que necesitaba la path fuera del contexto de la Route y llegué a la siguiente solución que también debería funcionar para usted:

 import { matchPath, useLocation } from "react-router-dom"; const routes = [ ':state/:city', ...otherRoutes ]; function usePathPattern() { const { pathname } = useLocation(); return matchPath( pathname, routes )?.path; }
over 4 years ago · Santiago Trujillo Report

0

No estoy seguro de si resuelve completamente su caso de uso, pero en mi caso usé una combinación de useLocation y useParams . Aquí está el código:

 import React from 'react'; import { useLocation, useParams } from 'react-router-dom'; import type { Location, Params } from 'react-router-dom'; /** * Function converts path like /user/123 to /user/:id */ const getRoutePath = (location: Location, params: Params): string => { const { pathname } = location; if (!Object.keys(params).length) { return pathname; // we don't need to replace anything } let path = pathname; Object.entries(params).forEach(([paramName, paramValue]) => { if (paramValue) { path = path.replace(paramValue, `:${paramName}`); } }); return path; }; export const Foo = (): JSX.Element => { const location = useLocation(); const params = useParams(); const path = getRoutePath(location, params); (...) };
over 4 years ago · Santiago Trujillo Report

0

Hice un enlace personalizado useCurrentPath con react-router v6 para obtener la ruta actual de la ruta, y funcionó para mí

Si la ruta actual es /members/5566 , obtendré la ruta /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 <></> }

Referencia

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!