#Is there a way to generate a To from the current location and some override params?

1 messages · Page 1 of 1 (latest)

hasty marsh
#

Here's the code I have to do this:

const matches = useMatches()
const navigate = useNavigate()
const navigateTo = useCallback(({ paramsOverrides }) => {
  const lastMatch = matches[matches.length - 1]
  const newParams = { ...lastMatch, ...paramsOverrides }
  const newPathname = lastMatch.id.replaceAll(/\$([^\/]+)/g, (_, pathParam) => {
    return newParams[pathParam]
  })
  navigate({ ...location, pathname: newPathname })
})

This seems like something the router should be able to do for me, but I can't find an API for it

hasty marsh
#

(And that code is totally broken. It doesn’t handle splat paths. It doesn’t handle root properly. This is exactly why I don’t want to maintain this!)

little forum
hasty marsh
#

Great start! generatePath takes as its first argument a known path template, but I’m in a component that could be shown on any page. Maybe I map from the last match’s ID to a path template

little forum
#

if you want to reconstruct the current parameterized path, you probably want to matchRoutes(location.pathname) and then you should be able to re-generate /:a/:b/:c from the match.route objects

hasty marsh
#

Great lead. Thank you!

hasty marsh
#

That doesn't seem to do what I would expect:

import { useLocation, useMatches } from '@remix-run/react'
import { matchRoutes } from 'react-router-dom'

const matches = useMatches(); // […]
const location = useLocation(); // { pathname, … }
matchRoutes(matches, location); // undefined

There's not much in the matchRoutes docs (https://reactrouter.com/en/main/utils/match-routes) , so I'm not sure I'm using it right, but the types to line up

little forum
#

ah - yeah the first param should be your routes

#

So what you passed to createBrowserRouter, or I think you could grab them from router.routes

hasty marsh
#

Does Remix expose the router instance? I don't see an API for it

little forum
#

Ah sorry I thought this was a react router app - missed the Remix tag up top