-
-
Save naeluh/3206352ad4718e9acf438a727b515765 to your computer and use it in GitHub Desktop.
Getting RAW (without URL decode) params from react-router-dom.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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