If you want to check if the current path is the root (/
) in React, you can do something like this using window.location.pathname
In React.js, you can retrieve the home page URL using different approaches depending on your setup. Here are two methods:
Using
window.location
Thewindow.location.origin
property provides the base URL of your site, andwindow.location.pathname
gives the current path.
Example:
TypeScript
const HomePage = () => { const homeUrl = window.location.origin; const isHomePage = window.location.pathname === '/'; return ( <div> <h1>Current URL: {homeUrl}</h1> <p>{isHomePage ? 'This is the Home Page' : 'This is not the Home Page'}</p> </div> );};export default HomePage;
Expand
- 2. Using
useLocation
from React Router If you’re using React Router for navigation, theuseLocation
hook provides access to the current path.
Example:
TypeScript
import { useLocation } from 'react-router-dom';
const HomePage = () => {
const location = useLocation();
const isHomePage = location.pathname === '/';
return (
<div>
<h1>{isHomePage ? 'This is the Home Page' : 'This is not the Home Page'}</h1>
</div>
);
};
export default HomePage;
Expand
Both methods can be used to check if the current URL corresponds to the home page (/
).
Advertisements