乐闻世界logo
搜索文章和话题

How to read the current full URL with React?

1个答案

1

Obtaining the current full URL in React can be done in multiple ways, primarily depending on whether you are using a routing library such as react-router. Below, I will explain how to retrieve the current full URL in both scenarios: when using react-router and when not using any routing library.

1. Using react-router

If your project integrates react-router, you can retrieve the current URL using the useLocation hook. Here is a specific example:

jsx
import React from 'react'; import { useLocation } from 'react-router-dom'; function CurrentUrlComponent() { const location = useLocation(); const currentUrl = window.location.origin + location.pathname + location.search + location.hash; return ( <div> Current URL is: {currentUrl} </div> ); }

In this example, the useLocation hook provides the location object, which contains detailed information about the current URL, such as the pathname (pathname), query parameters (search), and hash value (hash). window.location.origin is used to retrieve the domain and protocol part.

2. Without Using Any Routing Library

If your React project does not use react-router or any other routing library, you can directly use the JavaScript window.location object to retrieve the current URL:

jsx
import React from 'react'; function CurrentUrlComponent() { const currentUrl = window.location.href; return ( <div> Current URL is: {currentUrl} </div> ); }

In this example, window.location.href provides the complete URL of the current window.

Summary

Regardless of whether you are using react-router or directly accessing the global window object in JavaScript, retrieving the current URL is straightforward. With these methods, you can choose the most suitable approach based on your project's specific requirements.

2024年6月29日 12:07 回复

你的答案