Ivan Ortega Ivan Ortega - 1 year ago 204
Javascript Question

React-router force querystring to be an array with a single element

I just migrated an app made with

from an old version to
react 0.15
react-router 2.0

In the old version the
where created like this:

<Link to='route-name' query={{ids: [1]}}>

This constructed a url like
. That would give me in the component

this.props.query = {
ids: ['1']

After the upgrade the
declaration was changed to:

<Link to={{pathname:`/route/`, query={ids: [1]}}}>

Which produces urls like
, 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.

Answer Source

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} />