How To Get Current Route In React JS

Websolutionstuff | Aug-11-2023 | Categories : React JS

As a web developer using React JS, I've come to appreciate the power and efficiency of this JavaScript library. Its component-based approach and optimized rendering have transformed how we create dynamic and user-friendly interfaces.

However, as I ventured into building web applications, I realized the importance of smooth navigation through different views. This hinges on effective route management.

Welcome to our comprehensive guide on "How to Get the Current Route in React JS." Knowing how to access the current route is a crucial skill for creating strong and user-friendly React applications.

It enables us to implement dynamic rendering, handle conditional logic, and integrate complex features, all enhancing the user experience.

Throughout this article, I'll take you on a journey to explore various techniques and best practices for finding the current route in React JS.

Whether you're using popular routing libraries like React Router or crafting custom routing solutions, we've got you covered. With practical examples and step-by-step guidance, I aim to empower you to master this essential skill in React development.

So, let's dive in together and uncover the secrets of route management to unlock the full potential of your React applications

 

Step 1: Create a new React application

If you haven't already set up a React application, create one using Create React App (CRA), which provides a quick and easy way to bootstrap a new React project.

Open your terminal and run the following command.

npx create-react-app current-route-example
cd current-route-example

 

Step 2: Install React Router

To use React Router for handling routes in your application, you need to install the react-router-dom package.

The react-router-dom package contains bindings for using React Router in web applications. Please see the Getting Started guide for more information on how to get started with React Router.

Run the following command in your terminal.

npm install react-router-dom

 

Step 3: Set up the routes

In this step, you'll define the routes for your application. Open the src/App.js file and set up the routes using BrowserRouter and Route components from React Router.

import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
import Contact from './components/Contact';

const App = () => {
  return (
    <Router>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
        <Route path="/contact" component={Contact} />
        {/* Add more routes as needed */}
      </Switch>
    </Router>
  );
};

export default App;

 

 

Step 4: Create components for each route

In this step, create individual components for each route. These components will be rendered when the user visits the corresponding URL.

Create three new files in the src/components folder: Home.js, About.js, and Contact.js.

// src/components/Home.js
import React from 'react';

const Home = () => {
  return <h1>Welcome to the Home Page!</h1>;
};

export default Home;
// src/components/About.js
import React from 'react';

const About = () => {
  return <h1>About Us</h1>;
};

export default About;
// src/components/Contact.js
import React from 'react';

const Contact = () => {
  return <h1>Contact Us</h1>;
};

export default Contact;

 

Step 5: Access the current route

Now that you have set up the routes and components, you can access the current route within each component. React Router provides a useLocation hook to achieve this.

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

In any of your components (e.g., Home.js, About.js, or Contact.js), import the useLocation hook and use it to get the current route.

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

const Home = () => {
  const location = useLocation();
  const currentRoute = location.pathname;

  return (
    <div>
      <h1>Welcome to the Home Page!</h1>
      <p>Current Route: {currentRoute}</p>
    </div>
  );
};

export default Home;

useLocation() returns an object that contains information on the current page URL. Some of these properties are:

  • pathname: the part that comes after the domain name, e.g., /products.
  • search: the query string, e.g., ?id=5.
  • hash: the hash, e.g., #pricing.

Get dynamic route variable in React Router

To access the variables of a dynamic route directly in React Router, we use the useParams() hook.

For example:

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

function Posts() {
  const { id } = useParams();
  return <h2>Settings for post {id} </h2>;
}

export default function App() {

  return (
    <div>
      <div>
        <Routes>
          <Route path="/posts/:id" element={<Posts />} />
        </Routes>
      </div>
    </div>
  );
}

 

Step 6: Test the application

Now that everything is set up, start your development server to test the application.

npm start

Visit different routes (e.g., /about, /contact) in your application, and you will see that each component displays its respective content along with the current route.

Congratulations! You have successfully set up React Router in your application and learned how to access the current route using the useLocation hook.

 

Conclusion:

In conclusion, understanding how to get the current route in React JS is a valuable skill for web developers. It allows us to create dynamic and user-friendly applications by enabling smooth navigation, dynamic rendering, and the integration of complex features.

Throughout this guide, we've explored various techniques for achieving this, whether you're using popular routing libraries like React Router or custom solutions. With the knowledge gained here, you're well-equipped to navigate and manage routes effectively in your React applications.

 


You might also like:

Recommended Post
Featured Post
How To Add Ckeditor In Laravel
How To Add Ckeditor In Laravel

In this article, I will explain you how to add ckeditor in laravel, CKEditor is a WYSIWYG rich text edito...

Read More

Jun-18-2020

jQuery Image Magnifier on Mouse Hover
jQuery Image Magnifier on Mous...

In this article, we will see a jquery image magnifier on mouse hover. Using an image magnifier you can enlarge...

Read More

Jan-04-2021

How to Search with Pagination in Laravel 10 Vue 3
How to Search with Pagination...

Hey everyone! Ever found yourself in need of a straightforward example for integrating search and pagination in a Larave...

Read More

Jan-01-2024

Laravel 9 One To Many Polymorphic Relationship
Laravel 9 One To Many Polymorp...

In this article, we will see laravel 9 one to many polymorphic relationship. A one-to-many polymorphic relation is...

Read More

Apr-05-2022