How to get the current route using React Router

Photo of author

A renowned library for managing routing in React apps is called React Router. It offers a strong means of navigating between various parts or pages of an online application while keeping the code structure neat. This article will help you understand the routing state of your application by going over several ways to retrieve react router’s current route.

This article will cover the different ways and methods you can use to find the react router’s current route and establish new react routes. Some methods are getting the information of the current route, navigating through params, using the Router HOCs, etc. After reading this article, most of your doubts regarding this topic will be answered.

This detailed article will show you how to use React Router to get the current route and give you a better knowledge of the routing state of your application. We can help you access route parameters, programmatically browse between routes, and highlight the active route in your navigation menu.

After reading this article, you should be well-prepared to use React Router to manage and extract data from the routes in your application.

What is a React Router?

Let’s take a moment to recap what React Router is and why it’s important for web apps before we go into how to obtain the current route.

What is a React Router

A JavaScript module called React Router is used for declarative routing in React apps. It lets you specify how your application should be organized and how each component should appear depending on the URL. Single-page applications (SPAs) that resemble conventional multi-page web pages may be made with React Router.

Visit: What is a React Router?

Key features of React Router:

Without a doubt, these are the main characteristics of React Router, along with brief descriptions:

Declarative Routing

Simplify navigation in your React application by defining routes and related components using a declarative syntax.

Nested Routing

To enable hierarchical navigation, create intricate page architectures with routes inside routes.

Route Parameters

Utilise dynamic data extraction from URLs to create adaptable, data-driven interfaces.

Programmatic Navigation

Using the {history} object dynamically modifies routes based on application logic or user interactions.

Various Types of Routers

Select from various router kinds, such as `HashRouter` and `BrowserRouter,` to control the URL structure and history of the application.

Now, after knowing about the basics of react-router, let us know more specifically about the react-router current route.

Getting the current path

React Router provides a useLocation hook that you may use to get the path of the react router’s current route.

import { useLocation } from ‘react-router-dom’;

function CurrentRoutePath() {

const location = useLocation();

return (

<div>

<h2>Current Route Path</h2>

<p>{location.pathname}</p>

</div>

);

}

This example imports the useLocation hook from react-router-dom,’ which returns the location.pathname as the current URL pathname.

Accessing Route Parameters

In addition to the route path, React Router also lets you access route parameters. Route parameters are dynamic portions of the URL that may be retrieved for usage in your components. This helps in further identifying the react router’s current path.

import { useParams } from ‘react-router-dom’;

function UserProfile() {

const { username } = useParams();

return (

<div>

<h2>User Profile</h2>

<p>Username: {username}</p>

</div>

);

}

The route configuration used in this example is assumed to be /user/:username, where: username is a route parameter. The value of the username may be accessed from the URL with the useParams hook.

Checking the Active Route

You might sometimes wish to identify the react router’s current path to apply distinct styles or behaviors to the user interface components, such as the navigation menu. For this, React Router offers the useRouteMatch hook.

import { useRouteMatch } from ‘react-router-dom’;

function NavigationMenu() {

const isHomeActive = useRouteMatch(‘/’);

const isAboutActive = useRouteMatch(‘/about’);

const isContactActive = useRouteMatch(‘/contact’);

return (

<nav>

<ul>

<li className={isHomeActive ? ‘active’ : ”}><Link to=”/”>Home</Link></li>

<li className={isAboutActive ? ‘active’ : ”}><Link to=”/about”>About</Link></li>

<li className={isContactActive ? ‘active’ : ”}><Link to=”/contact”>Contact</Link></li>

</ul>

</nav>

);

}

In this example, we verify if the react router’s current route matches the given route pathways using the useRouteMatch hook.

See Also: How To Build React State Management Without Redux? 

Programmatically Navigating to a Route

You can programmatically browse an alternate route and read the current route in response to specific circumstances or user inputs. To do this, React Router provides the useHistory hook.

import { useHistory } from ‘react-router-dom’;

function LoginPage() {

const history = useHistory();

const handleLogin = () => {

// Perform authentication logic

// If authentication is successful, navigate to the user’s dashboard

history.push(‘/dashboard’);

};

return (

<div>

<h2>Login Page</h2>

<button onClick={handleLogin}>Login</button>

</div>

);

}

In this example, the history object—which offers navigational methods—is accessed using the useHistory hook. Upon successful login, the handle login method is triggered when the user hits the “Login” button and utilizes history. push to travel to the ‘/dashboard’ route.

See Also: Understanding The Purpose Of Index Route In React Router 

Navigating with Route Parameters

You may use the history.push function to browse a route with dynamic parameters by passing it an object containing the parameters and route path. Here’s one instance:

import { useHistory } from ‘react-router-dom’;

function UserProfile() {

const history = useHistory();

const handleViewProfile = (username) => {

// Navigate to the user’s profile with the username as a parameter

history.push(`/user/${username}`);

};

return (

<div>

<h2>User Profile</h2>

<button onClick={() => handleViewProfile(‘john_doe’)}>View John’s Profile</button>

<button onClick={() => handleViewProfile(‘jane_smith’)}>View Jane’s Profile</button>

</div>

);

}

In this example, the ‘handleViewProfile’ method receives the dynamic username as an argument, generates the URL, and points the user to the corresponding profile page.

See Also: Convert String To HTML In React: Rendering Text As HTML Content

Using the withRouter HOC (Higher Order Component)

Using the withRouter higher-order component is another method to obtain the current route information (HOC). This HOC gives you access to the match, history, and current location by injecting the router properties into your component. This is how to apply it:

import React from ‘react’;

import { withRouter } from ‘react-router-dom’;

class CurrentRouteInfo extends React.Component {

render() {

const { location, match, history } = this.props;

The code allows a React component to access and shows current route information without the need for hooks or context by injecting router-related properties (such as `location}, `match`, and `history}) into the component using the `withRouter} HOC. This is helpful when working with class-based components or components that aren’t directly connected to a route.

See Also: Link Image In React: Displaying Visual Content In React Components

FAQs

Why should I use React Router's `withRouter` HOC instead of hooks like `useLocation` or `useParams`?

React Router provides multiple ways to access the current route information. While hooks like `useLocation` and `useParams` are convenient for many scenarios, the `withRouter` HOC is particularly useful when working with class-based components or components not directly associated with a route. It allows you to inject router-related props into your component, making it aware of the current route without using hooks.

How can I determine the active route to highlight it in my navigation menu?

You can determine the active route using the `useRouteMatch` hook provided by React Router. By checking whether the react router current’s route matches a specified route path, you can apply different styles or behaviors to the active navigation menu item. This is useful for creating dynamic and user-friendly navigation interfaces.

Can I navigate to a route with dynamic parameters programmatically in React Router?

You can programmatically navigate to a route with dynamic parameters in React Router. Use the `use history` hook to access the `history` object, which provides methods like `push` for navigation. You can construct the URL with the necessary dynamic parameters and then call `history. push` to navigate to the desired react router current’s state. This is commonly used for user profile pages where the parameter (e.g., username) changes based on user interactions.

Conclusion

In conclusion, for efficient navigation and dynamic rendering, it is essential to comprehend how to get and use the current route in a React application using a React Router.

React Router offers flexible methods for retrieving and using route data, whether you want to utilize the `withRouter` Higher Order Component or hooks like `useLocation` and `useParams`.

You may develop strong, data-driven apps and a smooth user experience by managing route parameters, figuring out the active route, and obtaining insights into the current route path. With React Router, developers can easily create single-page apps by reducing the complexity of routing.

See Also: OnBlur Vs OnChange In React: Event Handling In Modern Web Apps

Leave a Comment