react-router generatePath with query parameters

Viewed 5967

I am using react-router's built in function generatePath to generate a URL. The issue is that as far as I understand this function just returns the path and doesn't provide a mechanism for us to know which fields were added in the path and which were not.

For example, for the following code

generatePath('/user/:id', {
    id: 1,
    name: 'John',
})

the function returns /user/1 which is correct, but there is no way for us to know that only id was inserted into the path and name needs to be passed as query parameters.
In my application both the path template and the params object are dynamic and I need to add the extra fields in params as the query parameters.
Is there any way to do that ?

1 Answers

For anyone checking now, I ended up using the path-to-regexp library which is the one used internally by react-router to generate the URL. The code looks something like this

import pathToRegexp from 'path-to-regexp';
import qs from 'qs';

const compiledCache = {};
export default function generatePathWithQueryParams(rawPath, params) {
    let toPath;
    if (compiledCache[rawPath]) {
        toPath = compiledCache[rawPath];
    } else {
        toPath = pathToRegexp.compile(rawPath);
        compiledCache[rawPath] = toPath;
    }
    const queryParams = { ...params };
    const path = toPath(params, {
        encode: (value, token) => {
            delete queryParams[token.name];
            return encodeURI(value);
        },
    });
    const queryString = qs.stringify(queryParams);
    if (queryString) {
        return `${path}?${queryString}`;
    }
    return path;
};
Related