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 Login With OTP In Laravel 10
How To Login With OTP In Larav...

In today's digital age, where security is paramount, user authentication has become a cornerstone concern for web ap...

Read More

Aug-21-2023

How To Image Upload Using Ajax In Laravel 9
How To Image Upload Using Ajax...

In this article, we will see how to image upload using ajax in laravel 9. Here, we will learn about image upload in...

Read More

Feb-07-2023

Laravel 11 Google Autocomplete Address Example
Laravel 11 Google Autocomplete...

Hello, laravel web developers! In this article, we'll see how to create a Google autocomplete address in laravel 11....

Read More

Jun-26-2024

How To Fix MySQL Shutdown Unexpectedly In XAMPP
How To Fix MySQL Shutdown Unex...

In this article, we will see how to fix "Error: MySQL shutdown unexpectedly" in XAMPP. When I open XAMPP...

Read More

Sep-22-2022