Connected-react-router: Example for query strings needed

Created on 13 Feb 2017  路  3Comments  路  Source: supasate/connected-react-router

Hi

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

/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

Your route would look like:

<Route path="/list" component={SomeComponent} />

Now somewhere in your app you can have a link, clicking which you will be taken to SomeComponent:

<Link to="/list?id=5&sort=true" />

And in your SomeComponent:

class SomeComponent extends React.Component {
    render() {
        const { location: { search } } = this.props;
    }
}

search will contain id=5&sort=true. You can use something like query-string to parse further

All 3 comments

Your route would look like:

<Route path="/list" component={SomeComponent} />

Now somewhere in your app you can have a link, clicking which you will be taken to SomeComponent:

<Link to="/list?id=5&sort=true" />

And in your SomeComponent:

class SomeComponent extends React.Component {
    render() {
        const { location: { search } } = this.props;
    }
}

search will contain id=5&sort=true. You can use something like query-string to parse further

In the case that your nested children components want to access the router state directly without passing from their parents' props, you can try this way.

import React from 'react'
import { connect } from 'react-redux'

const NestedChild = ({ pathname, search, hash }) => (
  <div>
    <div>
      pathname {pathname}
    </div>
    <div>
      search {search}
    </div>
    <div>
      hash {hash}
    </div>
  </div>

)

const mapStateToProps = state => ({
  pathname: state.router.location.pathname,
  search: state.router.location.search,
  hash: state.router.location.hash,
})

export default connect(mapStateToProps)(NestedChild)

I'm going to update the docs.

I already updated README and changed the example.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

dcs3spp picture dcs3spp  路  3Comments

jhwheeler picture jhwheeler  路  3Comments

abeledovictor picture abeledovictor  路  3Comments

AdrienLemaire picture AdrienLemaire  路  5Comments

zry754331875 picture zry754331875  路  3Comments