by Sai gowtham

Getting the current route in React router

In this tutorial, we are going to learn about how to get the current route path in react router.

Getting current route using hooks

With the react router v5, we can use the useLocation() hook to get the current route path in a router component.

Example:

Contact.js
import React from "react";
import { useLocation } from "react-router-dom";
export default function About() {
  const location = useLocation();
  console.log(location.pathname); // path is /contact
  return (
    <div>
      <h2>Contact</h2>
    </div>
  );
}

In the above code, we first imported the useLocation hook from the react-router-dom package, then inside the About component we accessed the current route using location.pathname property.

Getting the current route in class components

In class components, you can get the current route by using this.props.location.pathname property.

About.js
import React from "react";

class About extends React.Component {
  render() {
    console.log(this.props.location.pathname); // path is /about    return (
      <div>
        <h2>About</h2>
      </div>
    );
  }
}

export default About;

If you are using the react-router latest version, you need to use withRouter() higher-order component.

About.js
import React from "react";
import { withRouter } from "react-router-dom";
class About extends React.Component {
  render() {
    console.log(this.props.location.pathname); // path is /about    return (
      <div>
        <h2>About</h2>
      </div>
    );
  }
}

export default withRouter(About);

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 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)
221,520 students enrolled
44 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)
114,575 students enrolled
21 hours of video content
View Course