How To Get Current URL In React JS

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

As a React JS developer, I have come to appreciate the power and popularity of this remarkable JavaScript library. Its component-based approach and efficient virtual DOM have revolutionized the way we create interactive and dynamic user interfaces.

However, like many developers, I have often faced situations where I needed to access and manipulate the current URL of my React application.

Whether it's implementing dynamic routing, handling conditional rendering based on the URL, or integrating with external APIs that rely on the current URL, knowing how to obtain this information is essential.

I will explore various methods and techniques to seamlessly achieve this task in this article.

Together, we will dive into the world of React JS and uncover the best practices for retrieving the current URL in different scenarios.

By the end of this article, you'll be equipped with the knowledge and tools to confidently access the URL of your React application and pave the way for more sophisticated and personalized user experiences.

Let's embark on this journey and unravel the mysteries of obtaining the current URL in React JS, how to get the current URL in React JS, React JS get the current URL, and React get the current route.

 

Step 1: Create a new React application

If you haven't already set up a React application, you can create one using Create React App (CRA), a popular tool for bootstrapping React projects.

Open your terminal and run the following command.

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

 

Step 2: Create a functional component for the URL display

In this step, we'll create a functional component that will display the current URL on the screen. Create a new file UrlDisplay.js in the src folder and add the following code.

import React from 'react';

const UrlDisplay = ({ currentUrl }) => {
  return (
    <div>
      <h1>Current URL:</h1>
      <p>{currentUrl}</p>
    </div>
  );
};

export default UrlDisplay;

 

Step 3: Use React Router (Optional)

If you're using React Router for handling routing in your application, you can access the current URL using the useLocation hook provided by React Router. If you're not using React Router, you can skip this step.

Install React Router by running the following command.

npm install react-router-dom

Now, in your main component, typically App.js, import and use React Router.

import React from 'react';
import { BrowserRouter as Router, Route, Switch, useLocation } from 'react-router-dom';
import UrlDisplay from './UrlDisplay';

const App = () => {
  return (
    <Router>
      <Switch>
        <Route exact path="/" component={HomePage} />
        {/* Add other routes here */}
      </Switch>
    </Router>
  );
};

const HomePage = () => {
  const location = useLocation();
  const currentUrl = location.pathname;

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

export default App;

 

 

Step 4: Use window.location object (Without React Router)

If you're not using React Router and want to access the current URL directly, you can use the window.location object.

Update your App.js file (or any relevant component) to include the following code.

import React, { useEffect, useState } from 'react';
import UrlDisplay from './UrlDisplay';

const App = () => {
  const [currentUrl, setCurrentUrl] = useState('');

  useEffect(() => {
    setCurrentUrl(window.location.href);
  }, []);

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

export default App;

The window.location.href property returns a string that contains the entire page URL.

window.location contains other properties that give more information on the URL. Some of them are:

  • pathname: the path of the URL after the domain name and any optional port number.
  • protocol: the protocol scheme of the URL.
  • hostname: the hostname portion of the URL.

For Example:

export default function App() {
  const url = window.location.href;
  const pathname = window.location.pathname;
  const protocol = window.location.protocol;
  const hostname = window.location.hostname;

  return (
    <div>
      You are currently accessing <b>{url}</b><br />
      Pathname: <b>{pathname}</b><br />
      Protocol: <b>{protocol}</b><br />
      Hostname: <b>{hostname}</b>
    </div>
  );
}

 

Step 5: Test the application

Now, you can start your development server to test the application.

npm start

Your React application should now display the current URL on the screen, either using React Router or directly through the window.location object.

Congratulations! You've successfully created a React application that can retrieve and display the current URL. Whether you're using React Router or directly accessing the window.location object, this knowledge will be invaluable in various scenarios, especially when dealing with dynamic routing and personalized user experiences.

 


You might also like:

Recommended Post
Featured Post
Laravel 9 Resize Image Before Upload
Laravel 9 Resize Image Before...

In this article, we will see how to resize image before uploading in laravel 9. we will install the intervention/im...

Read More

Jun-15-2022

Laravel 8 Form Validation Example
Laravel 8 Form Validation Exam...

In this article, we will see the laravel 8 form validation example. form validation in laravel is a very common fun...

Read More

Oct-10-2020

Queen Elizabeth II Portrait Using CSS
Queen Elizabeth II Portrait Us...

In this article, we will see Queen Elizabeth II portrait using CSS. Elizabeth II was Queen of the United Kingd...

Read More

Sep-11-2022

Change Text Color Based On Background Color Using Javascript
Change Text Color Based On Bac...

In this article, we will see a change text color based on background color using javascript. Sometimes we have requ...

Read More

Dec-25-2020