by Sai gowtham

How to get the url params from a route in React

In this tutorial, we are going to learn about how to get the url params from a current route in react using react-router.

Getting the URL params

To get the url parameter from a current route, we can use the useParams() hook in react router v5.

Consider, we have a route like this in our react app.

<Route path="/users/:id" component={Users} />

Now, we can access the :id param value from a Users component using the useParams() hook.

Users.js
import React from "react";
import { useParams } from "react-router-dom";
export default function Users() {
  const { id } = useParams();
  return (
    <div>
      <h1>User id is {id}</h1>    </div>
  );
}

In React router v4, you can access it using the props.match.params.id.

Users.js
import React from "react";
import { useParams } from "react-router-dom";
export default function Users(props) {
  const { id } = props.match.params;
  return (
    <div>
      <h1>User id is {id}</h1>    </div>
  );
}

In class-based components, you can access it like this.

Users.js
import React, { Component } from "react";

class Users extends Component {
  render() {
    const { id } = this.props.match.params;
    return (
      <div>
        <h1>User id is {id}</h1>      </div>
    );
  }
}

export default Users;

If you don’t have a props object inside your react component, then you need wrap with a withRouter() higher-order function.

Users.js
import React, { Component } from "react";
import { withRouter } from "react-router-dom";
class Users extends Component {
  render() {
    const { id } = this.props.match.params;
    return (
      <div>
        <h1>User id is {id}</h1>
      </div>
    );
  }
}

export default withRouter(Users);

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course