I just migrated an app made with react
and react-router
from an old version to react 0.15
and react-router 2.0
In the old version the Links
where created like this:
<Link to='route-name' query={{ids: [1]}}>
{name}
</Link>
This constructed a url like /route/?ids[]=1
. That would give me in the component
this.props.query = {
ids: ['1']
}
After the upgrade the Link
declaration was changed to:
<Link to={{pathname:`/route/`, query={ids: [1]}}}>
{name}
</Link>
Which produces urls like /route/ids=1
, now the Router parses the querystring like this:
this.props.location.query = {
ids : '1'
}
The only way I've managed to get an array if is the array in the link declaration has more than one element, although the url doesn't use empty brackets in the url.
So is there a way to force the router to use an array when there is only a single element, I don't want to have to check every time if what I'm getting is an array or a string.
As described in the history docs, you need to use a custom history that parses the querystrings like you need it.
React-router uses the query-string
package for the parse and stringify functions, doing a quick glance of the code I don't think it supports your use case, fortunately the qs
package does it with just setting an options.
You'll need to do something like this:
import { stringify, parse } from 'qs'
import { Router, useRouterHistory } from 'react-router'
import createBrowserHistory from 'history/lib/createBrowserHistory'
const stringifyQuery = query => stringify(query, { arrayFormat: 'brackets' })
const history = useRouterHistory(createBrowserHistory)({ parseQueryString: parse, stringifyQuery })
<Router history={history} />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With