Skip to content

Instantly share code, notes, and snippets.

@naeluh
Forked from Kostanos/useRawParams.js
Created October 27, 2023 19:36
Show Gist options
  • Save naeluh/3206352ad4718e9acf438a727b515765 to your computer and use it in GitHub Desktop.
Save naeluh/3206352ad4718e9acf438a727b515765 to your computer and use it in GitHub Desktop.
Getting RAW (without URL decode) params from react-router-dom.
import { useContext, useMemo } from 'react';
// eslint-disable-next-line camelcase
import { UNSAFE_RouteContext, useParams } from 'react-router-dom';
/**
* Temporary workaround to get RAW params from react-router-dom v.6
* Should hanndle most of the simple cases like /:myVar/someVar/:mySecondVar
* @returns {Object} The same as useParams from react-router-dom but returns RAW (not URL decoded) paramters
*/
export default function useRawParams() {
const params = useParams();
const { matches } = useContext(UNSAFE_RouteContext);
const rawParams = useMemo(() => {
const retVal = {};
const match = matches[matches.length - 1];
const { pathname, route: { path: pathTemplate } } = match;
const pathParts = pathname.split('/');
pathTemplate
.split('/')
.forEach((pt, idx) => {
if (pt[0] === ':') {
retVal[pt.slice(1)] = pathParts[idx];
}
});
return retVal;
}, [params]);
return rawParams;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment