React Router Get Url Params

React Router is currently the de facto routing solution for react single page applications. React Router has some great features to offer and I usually end up using React Router for most of my react js applications.

One of the reasons that make React Router so popular is that it is very easy to use.  Here is how you can create routes using react router v4


<Route 
 path="/user/:userId" 
 component={UserComponent} />

The userId is the URL parameter and it can be accessed in the component of the Route i.e. UserComponent. Here is how you access the URL params in React Router V4


class UserComponent extends React.Component{
 render(){
  let userId = this.props.match.params.userId;
  // rest of the code
 }
}

To access the GET parameters of the URL we have to parse the query string of the URL by our selves. For that I use query-string package that does a brilliant job in parsing query string and return an object that contains all the GET parameters. Here is how we use it


import queryString from 'query-string';

class UserComponent extends React.Component{
 render(){
  // url is 'https://www.example.com/user?id=123&type=4';
  let url = this.props.location.search;
  let params = queryString.parse(url);
  console.log(params);
  // The result will be like below
  // { id: 123, type: 4 }
  // other code
 }
}

This how you can access url params and GET params using React Router V4

1 thought on “React Router Get Url Params”

  1. There can be another approach to get a parameter :
    //javascript
    let url = window.location.href;
    let param = window.location.pathname;
    // react
    let param1 = this.props.location.pathname;

Leave a Reply