React ~ Router ~ Query Strings - rohit120582sharma/Documentation GitHub Wiki

When you’re building for the web, sometimes you need to pass information via the URL. To do this, you can use a query string.


React Router (v4)

If you poke around on the location object that is passed to all components rendered by React Router, you’ll notice that it has a search property on it.

componentDidMount() {
    const { search } = this.props.location;
    console.log(search); // "?filter=top&origin=im
}

React Router (v5)

In order to get access to it, you use the useLocation custom Hook. useLocation returns a location object which has a search property whose value is the query string.

import { useLocation } from 'react-router-dom';

function App() {
    const { search } = useLocation();

    return (
        ...
    );
}

Pasring

But this is the literal query string. You’ll need to somehow parse it before you can get the actual values. You may be surprised to hear that React Router doesn’t come with built-in with support for parsing query strings.

React Router does not have any opinions about how you should parse URL query strings.

There are two common solutions. Either use the browser's URLSearchParams or use an external library query-string for parsing the query string.

import queryString from 'query-string';

...
// Browser API
const params = new URLSearchParams(search);
console.log(params.get('filter'), params.get('origin')); // "top", "im"

// External library
const values = queryString.parse(search);
console.log(values.filter, values.origin) // "top", "im"
⚠️ **GitHub.com Fallback** ⚠️