React - How to get parameter value from query string?

Franco picture Franco · Feb 12, 2016 · Viewed 811.1k times · Source

How can I define a route in my routes.jsx file to capture the __firebase_request_key parameter value from a URL generated by Twitter's single sign on process after the redirect from their servers?

http://localhost:8000/#/signin?_k=v9ifuf&__firebase_request_key=blablabla

I tried with the following routes configuration, but the :redirectParam is not catching the mentioned param:

<Router>
  <Route path="/" component={Main}>
    <Route path="signin" component={SignIn}>
      <Route path=":redirectParam" component={TwitterSsoButton} />
    </Route>
  </Route>
</Router>

Answer

Christian picture Christian · Jun 1, 2016

React Router v4 and React Router v5, generic

React Router v4 does not parse the query for you any more, but you can only access it via this.props.location.search. For reasons see nbeuchat's answer.

E.g. with qs library imported as qs you could do

qs.parse(this.props.location.search, { ignoreQueryPrefix: true }).__firebase_request_key

Another library would be query-string. See this answer for some more ideas on parsing the search string. If you do not need IE-compatibility you can also use

new URLSearchParams(this.props.location.search).get("__firebase_request_key")

For functional components you would replace this.props.location with the hook useLocation. Note, you could use window.location.search, but this won't allow to trigger React rendering on changes. If your (non-functional) component is not a direct child of a Switch you need to use withRouter to access any of the router provided props.

React Router v3

React Router already parses the location for you and passes it to your RouteComponent as props. You can access the query (after ? in the url) part via

this.props.location.query.__firebase_request_key

If you are looking for the path parameter values, separated with a colon (:) inside the router, these are accessible via

this.props.match.params.redirectParam

This applies to late React Router v3 versions (not sure which). Older router versions were reported to use this.props.params.redirectParam.

General

nizam.sp's suggestion to do

console.log(this.props)

will be helpful in any case.