reactjsreact-routerquery-stringurl-parameters

How to get parameter value from query string?


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>

Solution

  • React Router v6, using hooks

    In react-router-dom v6 there's a new hook named useSearchParams. So with

    const [searchParams, setSearchParams] = useSearchParams();
    searchParams.get("__firebase_request_key")
    

    you will get "blablabla". Note, that searchParams is an instance of URLSearchParams, which also implements an iterator, e.g. for using Object.fromEntries etc.

    React Router v4/v5, without hooks, generic

    React Router v4 does not parse the query for you any more, but you can only access it via this.props.location.search (or useLocation, see below). 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.