React provides powerful tools for creating dynamic web apps. The two most important hooks for dealing with routing and URLs are useLocation and useParams. In this blog post, we’ll explore these hooks’ functionality, discuss their application with examples, and show you how to combine them to give your React projects smooth navigation.
Understanding useLocation
The useLocation hook is provided by React Router and allows components to access detailed information about the current URL. It returns an object containing various properties, each representing a different aspect of the URL. Let’s explore each of these properties:
pathname: Represents the current path of the URL.
search: Represents the query string parameters of the URL.
hash: Represents the hash portion of the URL.
state: Represents any state information associated with the location.
Exploring Each Property
Now, let’s delve into each property returned by useLocation and understand its significance with practical examples.
Accessing Current Pathname
The “current path” parameter in the useLocation hook is represented by the pathname property of the location object. It provides information about the URL’s current path, which corresponds to the user’s current route. This parameter is useful for determining the active route and rendering components conditionally based on the route path.
Let’s create an example to demonstrate how to use the “current path” parameter in useLocation:
import React from 'react'; import { useLocation } from 'react-router-dom'; const LocationInfo = () => { const location = useLocation(); return ( <div> <h1>Location Information</h1> <h3>Current Path: {location.pathname}</h3> </div> ); } export default LocationInfo;
In this example, we import useLocation from react-router-dom and use it to access the current location object. We then display the location object’s pathname property in the JSX, which represents the current path of the URL.
Output:
Retrieving Query Parameters
The search parameter in the useLocation hook represents the query string parameters of the URL.
What is a query parameter?
A key-value pair is included at the end of a URL and is known as a ‘query parameter.’ It is usually followed by ? and separated by &. Information flows between pages via a query parameter. For example, in the URL
http://website.com /articles?category=technology&sort=date, the search parameter is ? category=technology&sort=date. Here, category and sort are the query parameters, and their values are technology and date.
Let’s create an example to demonstrate how to use the search parameter in useLocation:
import React from 'react'; import { useLocation } from 'react-router-dom'; const LocationInfo = () => { const location = useLocation(); // Extracting search parameters const searchParams = new URLSearchParams(location.search); console.log(location); const category = searchParams.get('category'); console.log(category) const query = searchParams.get('sort'); return ( <div> <h2>Location Information</h2> <p><strong>Current Path:</strong> {location.pathname}</p> <p><strong>Search Params:</strong> {location.search}</p> <p><strong>Query:</strong> {query}</p> <p><strong>Category:</strong> {category}</p> </div> ); } export default LocationInfo;
In this example, we import useLocation from react-router-dom and use it to access the current location object. We then create a URLSearchParams object from the search property of the location object to parse the query parameters. We extract specific query parameters using the get() method of the URLSearchParams object and display them in the JSX.
Output:
Accessing Hash Fragment
The hash parameter in the useLocation hook represents the hash portion of the URL. The hash portion of a URL is typically used to navigate within a single HTML page by jumping to a specific section, often referred to as an anchor link. A hash is preceded by the symbol # and can contain any valid URL-encoded character.
For example, in the URL https://example.com/#about, the hash parameter is #about. Here, about is the hash value, indicating that the page should scroll to the section with the ID “about.”
Let’s create an example to demonstrate how to use the hash parameter in useLocation:
import React from 'react'; import { useLocation } from 'react-router-dom'; const LocationInfo = () => { const location = useLocation(); return ( <div> <h2>Location Information</h2> <p><strong>Current Path:</strong> {location.pathname}</p> <p><strong>Hash:</strong> {location.hash}</p> </div> ); } export default LocationInfo;
Output:
Retrieving State Information
The state parameter in the useLocation hook represents any state information associated with the location. It allows additional data to be passed along with route transitions, which can be useful for scenarios where complex data needs to be passed between routes.
Let’s create an example to demonstrate how to use the state parameter in useLocation:
import React from 'react'; import { useLocation } from 'react-router-dom'; const LocationInfo = () => { const location = useLocation(); return ( <div> <h2>Location Information</h2> <p><strong>Current Path:</strong> {location.pathname}</p> <p><strong>State:</strong> {JSON.stringify(location.state)}</p> </div> ); } export default LocationInfo;
Output:
Note: You can also access the location state directly from history.location, but it’s not recommended because it’s mutable. It’s better to use the location object passed to your components by React Router, as it ensures immutability.
You can access the location object in React Router to determine when navigation occurs. This is particularly helpful for tasks like data fetching or triggering animations based on route changes. The location object remains unchanged throughout the lifecycle, allowing you to use it effectively in lifecycle hooks for navigation-related tasks.
Exploring useParams
useParams, a hook that react-router-dom provides, lets you access the parameters of the current route. This proves particularly useful when you create applications requiring dynamic routing, where the URL contains variable parts that you aim to capture and utilize within your component.
Let’s walk through a complete example of using useParams in a React application. We’ll build a simple blog post viewer where the post ID is part of the URL.
Home Component (Home.js)
The Home component is a functional component that renders the homepage of our blogging platform. It displays a list of blog posts with links to individual post pages.
// src/Home.js import React from "react"; import { Link } from "react-router-dom"; function Home() { const posts = [ { link: "/post/1", name: "Post 1" }, { link: "/post/2", name: "Post 2" }, { link: "/post/3", name: "Post 3" }, ]; return ( <div className="container"> <h1>Blog Posts</h1> <ul> {posts.map(({link, name}) => ( <li> <Link to={link}>{name}</Link> </li> ))} </ul> </div> ); } export default Home;
Post Component (Post.js)
The Post component is also functional. It retrieves the post ID from the URL using the useParams hook provided by react-router-dom. Then, it fetches and displays the corresponding blog post content.
// src/Post.js import React from "react"; import { useParams } from "react-router-dom"; function Post() { let { postId } = useParams(); return ( <div className="container"> <div className="post"> <h2>Post ID: {postId}</h2> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam nec ligula sit amet justo malesuada facilisis. Integer sodales, ligula id fringilla posuere, justo ex cursus turpis, at tempus risus lectus in nisi. </p> </div> </div> ); } export default Post;
Output:
Conclusion:
In this blog post, we’ve explored the useLocation and useParams hooks in React Router and demonstrated their usage with practical examples. You can build responsive and dynamic components that work with the URL in your React applications with ease by utilizing these hooks. Knowing and using these hooks will improve your routing and user experience regardless of the complexity of the web application you’re developing. Happy routing!