Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 500
Ivan Ortega Avatar asked Mar 07 '16 19:03

Ivan Ortega


1 Answers

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} />
like image 200
alejandrodnm Avatar answered Sep 30 '22 14:09

alejandrodnm