React is a popular JavaScript library for building user interfaces and single-page applications. If you're building websites with React, chances are you'll need to handle URL parameters at some point.
This can sound tricky, especially because React doesn't give you a direct way to access URL parameters. But don't worry, we've got you covered.
In this article, you'll learn what URL parameters are, and how are they being used in modern websites. We'll learn how to get URL parameters in React. And we'll also see how to use React Router to process these parameters.
But first, let's start with a quick overview of URL parameters.
What Are URL Parameters
URL parameters are essentially variables that are passed through the URL to help identify specific content or actions on a website.
note
URL parameters are the part of a URL that comes after the ?
character. They are used to provide additional information to a web server or application.
They can be used for a variety of purposes, such as controlling the content of a web page, or the behavior of a web application.
URL parameter is a way to pass information about a click, through its URL. You can insert URL parameters into your URLs so that your URLs track information about a click. URL parameters are made of a key and a value separated by
=
and joined by an ampersand&
. The first parameter always comes after a question mark in a URL. (source: Google)
URL parameters are typically in the form of key-value pairs, with the key being the name of the parameter and the value being the value that is passed. For example, the URL www.example.com?name=John&age=30 would have two URL parameters, name
and age
, with respective values of John
and 30
.
info
URL parameters are typically encoded using the "URL encoding" standard.
With all this information in mind, we should have a solid understanding of what URL parameters are. And now, let's see how are they being used.
How Are URL Parameters Being Used
URL parameters are often used to control how a web page or application behaves. For example, a URL parameter may be used to specify the language in which a web page should be displayed.
URL parameters can also be used for tracking purposes. For example, a website may use a URL parameter to track the number of times a user has visited a particular page.
The applications for utilizing URL parameters are endless. However, there are common use cases that are almost always handled using URL parameters.
Common uses for URL parameters include:
- User tracking
- Searching
- Paginating
- Sorting
- Filtering
- Translating
tip
If you need to cover any of these use cases in your website, URL parameters are definitely a way to go.
How to Get URL Parameters in React
When it comes to getting URL parameters in React, react-router-dom
provides a handy set of utilities that can be used to make working with URL parameters easier. However, you don't need to use this package in order to work with URL parameters. All you need is window
object and URLSearchParams
interface.
The URLSearchParams interface defines utility methods to work with the query string of a URL. An object implementing URLSearchParams can directly be used in a for...of structure to iterate over key/value pairs in the same order as they appear in the query string. (source: MDN)
Get URL Parameters Using Window
You can extract the information about URL parameters directly from window
object. And process it using URLSearchParams
interface.
caution
This method won't handle changes in the URL. It will only process URL parameters when the component mounts.
Getting search parameters using window
const App = () => {
const params = new URLSearchParams(window.location.pathname);
return <p>{params.get("userId")}</p>;
};
export default App;
For the more sophisticated approaches, we'll make use of React Router and its utilities.
React Router is a fully-featured client and server-side routing library for React. (source: React Router)
Get URL Parameters Using React Router v6
If you're using React Router v6, you can make use of useSearchParams
hook. This hook makes it super simple to get URL query parameters, and it also handles updates to the URL.
The
useSearchParams
hook is used to read and modify the query string in the URL for the current location. Like React's ownuseState
hook,useSearchParams
returns an array of two values: the current location's search params and a function that may be used to update them.
Getting search parameters using React Router v6
import { useSearchParams } from "react-router-dom";
const App = () => {
const [searchParams] = useSearchParams();
return <div className="App">{searchParams.userId)}</div>;
};
export default App;
Unfortunately, this hook is only available in the v6 of React Router. If you're using older versions of this library, you have to reach out to other solutions.
Get URL Parameters Using React Router v4/v5
In the previous version of React Router, they don't support parsing of the URL search parameters out of the box, which means we have to do it ourselves. This is not such a big deal, especially because we can still use useLocation
hook to our advantage.
useLocation
hook returns the current location object. This can be useful if you'd like to perform some side effects whenever the current location changes. (source: React Router)
We can extract the information about URL parameters from this hook, and combine it with URLSearchParams
interface. Using this technique, we can read URL parameters from the URL, and listen for the changes in the URL at the same time.
Getting search parameters using React Router v4/v5
import { useLocation } from "react-router-dom"
const App = () => {
const location = useLocation()
const params = new URLSearchParams(location.search)
return (
<div className="App">
{params.get("userId")}
</div>
);
}
export default App
Concluding Thoughts
URL parameters are a great way to pass information to a web page or web application. The concept of URL parameters is fairly simple, but yet plenty effective. And it's no surprise that we see their usage in almost every modern website out there.
If you've read the article carefully, you should understand what URL parameters are and how they are being used. You should also know how to identify them in any URL. And on top of that, you should know how to properly use them in React websites.
With everything we've learned today, it's time to start using this knowledge. And utilize the URL parameters where needed.