How To Get Current Route In React JS

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

As a web developer working with React JS, I've experienced the sheer power and efficiency of this JavaScript library firsthand. Its component-based approach and optimized rendering have elevated the way we create dynamic and engaging user interfaces.

But, as I embarked on building web applications, I quickly realized the significance of smooth and seamless navigation through different views, which relies heavily on effectively managing routes.

Welcome to our comprehensive guide on "How to Get Current Route in React JS." Understanding how to retrieve the current route is a vital aspect of creating robust and user-friendly React applications.

It allows us to implement dynamic rendering, handle conditional logic, and integrate complex features, all of which contribute to an enhanced user experience.

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

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

So, let's dive in together and uncover the secrets of managing routes 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.

 


You might also like:

Recommended Post
Featured Post
How To File Upload In Angular 15 Example
How To File Upload In Angular...

As an Angular 15 developer, I understand the significance of incorporating file upload functionality into web applicatio...

Read More

Jun-19-2023

Laravel AJAX CRUD example
Laravel AJAX CRUD example

Today I will show you how to create ajax crud operations in laravel. In laravel 6/7 ajax crud operation, we can perform...

Read More

May-14-2020

Import Export CSV/EXCEL File In Laravel
Import Export CSV/EXCEL File I...

Today I will show you how to implement/install the import/export package in laravel 6/7. We will simply create...

Read More

May-19-2020

Autocomplete Search using Bootstrap Typeahead JS
Autocomplete Search using Boot...

In this example we will see autocomplete search using bootstrap typeahead js.Typeahead search is a method for progr...

Read More

Jun-09-2021