React-router: [V4] Example for Query Strings needed

Created on 13 Feb 2017  路  1Comment  路  Source: ReactTraining/react-router

Hi

Could you please provide an example how to deal with query strings in V4.

/list?id=5&sort=true

how would a <Route> look like that matches and how to extract the params id and sort?

Most helpful comment

The search string is not used in matching locations, only the pathname.

<Route path='/list' component={List} />

You can parse the current location.search string to get the query params as an object. There are a lot of different options for parsing/stringifying query objects. qs is a popular one.

import { parse } from 'qs'

const List = ({ location }) => {
  const query = parse(location.search.substr(1)))
  return (
    <ul>
      <li>ID: {query.id}</li>
      <li>Sort: {query.sort}</li>
    </ul>
  )
}

>All comments

The search string is not used in matching locations, only the pathname.

<Route path='/list' component={List} />

You can parse the current location.search string to get the query params as an object. There are a lot of different options for parsing/stringifying query objects. qs is a popular one.

import { parse } from 'qs'

const List = ({ location }) => {
  const query = parse(location.search.substr(1)))
  return (
    <ul>
      <li>ID: {query.id}</li>
      <li>Sort: {query.sort}</li>
    </ul>
  )
}
Was this page helpful?
0 / 5 - 0 ratings