Hey guys, This React tutorial helps to explore different techniques within React to obtain the current URL in the React application. We’ll discuss one-by-one technique with examples.
We’ll discuss following techniques into this article,
- Using window.location
- Integrating with React Router
- Using Hooks and Context
- Redux with React Hooks
You can also check other tutorial of React,
- React Layout Using Material Design
- React Datetime Picker with Example
- Learn React File Upload In 5 Minute
- React Select Example Using Material UI
Using window.location
The JavaScript has the window.location
object to access information about the current URL. The window.location
object provides various properties such as href
, pathname
, search
, hash
, and more. We’ll use href
property to get the current url.
Example:
const currentUrl = window.location.href;
Example Using React Component:
import React, { useEffect } from 'react'; const MyComponent = () => { useEffect(() => { // Get the current URL const currentUrl = window.location.href; console.log('Current URL:', currentUrl); // Get specific components of the URL const pathname = window.location.pathname; console.log('Pathname:', pathname); }, []); return ( // Your component JSX <div> {/* Your component content */} </div> ); }; export default MyComponent;
The window.location.href
property returns the complete URL, while window.location.pathname
return the specific component url.
Get Current URL Using React Router
React Router is a widely used library for managing routing in React applications. The useLocation
hook is part of the React Router library and provides a location
object, which contains details about the current URL.
import { useLocation } from 'react-router-dom'; const YourComponent = () => { const location = useLocation(); const currentPath = location.pathname; };
In the above example, I have imported useLocation
hook from 'react-router-dom'
library. The location object obtained from this hook contains information about the current URL.
Using Hooks and Context
We can also use hooks and context to manage the current URL within our application state. Create a Custom Hook with useState
and useEffect
hooks.
import { useState, useEffect } from 'react'; const useCurrentUrl = () => { const [currentUrl, setCurrentUrl] = useState(window.location.href); useEffect(() => { const handleUrlChange = () => setCurrentUrl(window.location.href); window.addEventListener('popstate', handleUrlChange); return () => window.removeEventListener('popstate', handleUrlChange); }, []); return currentUrl; };
UseCurrentUrl
is a React hook that initializes state with the current URL. Using useEffect
, it subscribes to URL changes and modifies the state as needed. When the component unmounts, the event listener is removed and the current URL is returned.
Using Hooks and Redux
We can use redux for state management in the react application, Which Stores the current URL in the application state and allows easy access from any component.
// actions.js export const setUrl = (url) => ({ type: 'SET_URL', payload: url }); // reducer.js const initialState = { currentUrl: window.location.href }; const urlReducer = (state = initialState, action) => { return action.type === 'SET_URL' ? { ...state, currentUrl: action.payload } : state; }; // useCurrentUrl.js import { useEffect } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { setUrl } from './actions'; const useCurrentUrl = () => { const dispatch = useDispatch(); const currentUrl = useSelector((state) => state.currentUrl); useEffect(() => { const handleUrlChange = () => dispatch(setUrl(window.location.href)); window.addEventListener('popstate', handleUrlChange); return () => window.removeEventListener('popstate', handleUrlChange); }, [dispatch]); return currentUrl; };
Conclusion:
We explored different technique to get current url in react application, Each option(window.location, React Router and redux) has own pros and cons. You can use any of them as per your project requirement and state management requirements.