Get the current route using React Router

To get the current route with React Router, use the useLocation() hook. The useLocation() hook returns the current location object. We can use the pathname property of the location object to get the current route without the domain name. This location object also returns the hash and search of the current URL.

The useLocation hook is only available from react-router >= 5.1 and React >= 16.8.

The below example shows how to use useLocation hook to get the current route.

import React from 'react';
import {Route, Link, Routes, useLocation} from 'react-router-dom';


export default function App() {
  	return (		
		<div>
			<ul>
				<li>
					<Link to="/">Home</Link>
				</li>
				<li>
					<Link to="/products">Products</Link>
				</li>
			</ul>
			<Routes>		
				<Route path="/products" element={<Products />} />
				<Route path="/" element={<Home />} />
			</Routes>
		</div>	
	);
}

function Home() {
	const location = useLocation();
  	return <>
		<h2>Current Pathname {location.pathname}</h2>
		<p>Home Page</p>
	</>;
}

function Products() {
	const location = useLocation();
  	return <>
		<h2>Current Pathname {location.pathname}</h2>
		<p>Products Page</p>
	</>;
}

In the above example, we have used useLocation() hook to get the current location object. 

The properties available in the location object are given below.

  1. pathname - the current pathname of current URL without domain name. e.g. /products
  2. search - the current query string parameters of current URL. e.g. ?page=10
  3. hash - the current hash, e.g. #example.

To use useLocation() hook, we have to wrap the App component inside BrowserRouter as given below.

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import reportWebVitals from './reportWebVitals';
import {BrowserRouter} from 'react-router-dom';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  	<React.StrictMode>
    	<BrowserRouter>
      		<App />
    	</BrowserRouter>
  	</React.StrictMode>
);

reportWebVitals();

To get the full URL with the domain name, we can use window.location.href. It will return a URL like ‘https:www.example.com/products?page=10’.

We can use of useParams hook to get an object of key/value pairs of URL dynamic parameters.

Current route using React Router in Class Component

We can get the current route inside the class component via the withRouter higher-order component. It will pass updated match, location, and history props to the wrapped component whenever it renders. 

The withRouter the higher-order component has been removed in react-router v6. Version 5.2.0 of react-router support withRouter. We can install the respective version with the command npm install [email protected] The below example shows how to use withRouter in class component.

import React from "react";
import { withRouter } from "react-router";

// A simple component that shows the pathname of the current location
class Product extends React.Component {
  	render() {
    	return <div>You are now at {this.props.location.pathname}</div>;
  	}
}

// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const ProductComponent = withRouter(Product);

export default ProductComponent;

In the above code, we imported withRouter from react-router in the top. The react component Product was wrapped with withRouter higher-order component as given below. 

const ProductComponent = withRouter(Product);

Then ProductComponent was exported from the file.

Conclusion

The useLocation() hook return location object with information about the current URL. The pathname property of location object has a value of the current URL path without a domain name. we can use of withRouter higher component to get current URL details in class component.

 

Related Blogs

Can't Perform a React State Update on an Unmounted Component

Can't Perform a React State Update on an Unmounted Component

React Warning “Can't perform a react state update on an unmounted component” is caused when we try to update the state after the component was unmounted. Explains how to fix it.

Each child in a list should have a unique key prop

Each child in a list should have a unique key prop

Solve Warning: Each child in a list should have a unique ”key" prop in React by setting the id property as a unique key or by auto-assigning unique keys.

React Hook is Called Conditionally

React Hook is Called Conditionally

Error: "React Hook is called conditionally. React Hooks must be called in the exact same order in every component render" occurs when hooks are invoked conditionally or after a return of a value.

Too many re-renders. React limits the number of renders to prevent an infinite loop

Too many re-renders. React limits the number of renders to prevent an infinite loop

The React error "Too many re-renders. React limits the number of renders to prevent an infinite loop" happens when you have reached an infinite render loop.

Adjacent JSX elements must be wrapped in an enclosing tag

Adjacent JSX elements must be wrapped in an enclosing tag

The "Adjacent JSX elements must be wrapped in an enclosing tag" error can be solved by wrapping the multiple elements in a parent div or in a react fragment

The tag is unrecognized in this browser

Warning: The tag is unrecognized in this browser

Warning "The tag is unrecognized in this browser" occurs when the tag doesn't exist in the browser or when we render a component starting with a lowercase letter.

The style prop expects a mapping from style properties to values, not a string

The style prop expects a mapping from style properties to values, not a string

"The style prop expects a mapping from style properties to values, not a string" React error occurs when we pass a CSS string to the style attribute.

Pass event and parameter onClick in React

How to pass event and parameter onClick in React

We set the inline arrow function (event) => clickHandler(event, "Hello World!") as props to the onClick event handler in the button. The arrow function takes the event as an argument and calls the clickHandler function.

Create a Back button with React Router

Create a Back button with React Router

To create a back button with React Router use useNavigate() hook. Call navigate function eg. navigate(-1); inside the onClick function of the back button.