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 (
        <NavLink to={"/route1"}>Link 1</NavLink>
        {" | "}
        <NavLink to={"/route2"}>Link 2</NavLink>
      <div style={{ marginTop: 20 }}>
          component={() => {
            return <div>Click on above links to see the effect</div>;
        <Route path="/route1" component={RouteComponent} />
        <Route path="/route2" component={RouteComponent} />

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

    Tweet this to help others

Live Demo

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like