You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I recently had reason to set a router param programatically and wondered why the method wasn't already a feature of the library. It would assume a similar pattern to the useParams hook but would instead provide a way to navigate with a replace=true (no refresh) while reducing boilerplate.
Here's my rough POC:
// ...setParams({uuid: thing.uuid});// ...
import{useCallback}from'react';import{useNavigate,useLocation,matchRoutes,generatePath}from'react-router-dom';/** * will update the params present in the routes object for the active * route (ex: `/my-route/:uuid/whatever-else` where `uuid` can be hot-swapped) * without causing a full page refresh or any sketchy business with just * appending the params to the end of `location.pathname` * * for instance, calling `setParams({ uuid: '123abc' })`: * - `/my-route/:uuid` will be set into the url as `/my-route/123abc` * - `/my-route/:uuid/whatever-else` will be set into the url as `/my-route/123abc/whatever-else` */constuseSetParams=(routes: Parameters<typeofmatchRoutes>[0])=>{constlocation=useLocation();constnavigate=useNavigate();constmatchedRoute=matchRoutes(routes,location.pathname)?.at(-1);// assumes the most specific match is the last one in the cascadeconstsetParams=useCallback((params: {[key: string]: string})=>{if(matchedRoute){constpath=generatePath(matchedRoute.route.path,{
...matchedRoute.params,
...params,});if(path!==location.pathname)navigate(path,{replace: true});}else{console.warn('Failed to determine matched route');}},[matchedRoute],);return{actions: {
setParams,},};};exportdefaultuseSetParams;
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
I recently had reason to set a router param programatically and wondered why the method wasn't already a feature of the library. It would assume a similar pattern to the
useParams
hook but would instead provide a way tonavigate
with areplace=true
(no refresh) while reducing boilerplate.Here's my rough POC:
Beta Was this translation helpful? Give feedback.
All reactions