React Router DOM – Get current route

React router dom – get current route using useLocation hook provided by v5.1 library. It will return all the properties which you get from window.location in javascript.

import {useLocation} from 'react-router-dom'

const location = useLocation();
// location.pathname

Complete code –

import React from "react";
import { BrowserRouter, Route, NavLink, useLocation } from "react-router-dom";

export default function App() {
  return (
    <BrowserRouter>
      <div>
        <NavLink to={"/route1"}>Link 1</NavLink>
        {" | "}
        <NavLink to={"/route2"}>Link 2</NavLink>
      </div>
      <div style={{ marginTop: 20 }}>
        <Route
          path="/"
          component={() => {
            return <div>Click on above links to see the effect</div>;
          }}
        />
        <Route path="/route1" component={RouteComponent} />
        <Route path="/route2" component={RouteComponent} />
      </div>
    </BrowserRouter>
  );
}

const RouteComponent = () => {
  const location = useLocation();
  return (
    <div style={{ marginTop: 20 }}>
      Location Path: <b>{location.pathname}</b>
      <p>Location Object: {JSON.stringify(location)}</p>
    </div>
  );
};

    Tweet this to help others

Live Demo

Open Live Demo