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) from a url 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);

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2021 (Beginner + Advanced)
JavaScript - The Complete Guide 2021 (Beginner + Advanced)
64,026 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 - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
152,857 students enrolled
48.5 hours of video content
View Course