Skip to content

Instantly share code, notes, and snippets.

@Kostanos
Created July 16, 2022 17:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Kostanos/e3cc71b6263846cdd887395f505076c8 to your computer and use it in GitHub Desktop.
Save Kostanos/e3cc71b6263846cdd887395f505076c8 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