5

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.

2 Answers 2

9

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} />
Sign up to request clarification or add additional context in comments.

Comments

1

I recommend the qs package.

import { stringify } from 'qs';

var queryStr = stringify({ ids: [21] }, { encode: false });

2 Comments

Thanks David, but not found... :(
The qs package gives you the string url, but the thing is that react-router parses the url and returns a string instead of an Array in the query object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.