How to get URL query parameter value from query string in ReactJS?

Getting a query parameter value from the URL in ReactJS is easy. We can do it in multiple ways.

In React if you use the router component then it will pass the location object to the RouteComponent as props. We could simply use that using this.props.location.search

We can just retrieve it by writing a custom function. But it is always good to use component for this. We can use query-string component for this.

How to install query-string component?

If we have npm or yarn we can install it in the following ways:

$ npm install query-string
or
$ yarn add query-string

How to use it?

Once we have the dependency added we can simply do the following in our react code.

import queryString from 'query-string'; 
 
// Sample url: https://example.com/thankyou?status=success
class Thankyou extends React.Component {
    componentDidMount() {
        let queryStrObj = queryString.parse(this.props.location.search);
        console.log(queryStrObj.status);
    }