Reputation: 9273
I'm trying to handle multiple parameters in react router with the same name, i make an example to explain me better, i have a page in which I compare some items through the id of the item, so for example in a query string I have an array:
&resourceid[]=123&resourceid[]=456...
so in this way I can have n-resourceid values. How can I achieve something like that in react router? I have found this answer:
Multiple IDs with React Router
but it binds me with a specific number of ids and with multiple and different name for example /compare/:id1/:id2/:id3....
I don't know how many item can I have so I want something more elastic like the query string array example above.
Any idea?
Thanks
Upvotes: 1
Views: 2218
Reputation: 15106
React-router v4 doesn't parse the query string anymore, see https://github.com/ReactTraining/react-router/issues/4410. You can do it yourself with the query-string
package though. Either parse the query on mount & receive props, or do it in a wrapper component, like this:
import * as qs from 'query-string';
const Wrapper = (props) => {
const parsedQueryParams = qs.parse(props.location.search, {arrayFormat: 'bracket'});
return <YourComponent {...props} resourceid={parsedQueryParams.resourceid}/>;
};
Upvotes: 1
Reputation: 922
Maybe a customHistory will do the trick:
import { stringify, parse } from 'qs'
import { Router, useRouterHistory } from 'react-router'
import createBrowserHistory from 'history/lib/createBrowserHistory'
const stringifyQuery = query => stringify(query, { arrayFormat: 'brackets', encode: false })
const history = useRouterHistory(createBrowserHistory)({ parseQueryString: parse, stringifyQuery })
<Router history={history} />
Check this issue for the discussion: https://github.com/ReactTraining/react-router/issues/939
Upvotes: 0