Welcome to this comprehensive guide on Query Parameters in React JS! 🎉
By the end of this tutorial, you'll understand how to handle query parameters in your React applications, making them more dynamic and user-friendly. Let's dive in!
Query parameters are additional information passed to a URL, allowing dynamic data to be sent and received between the client (browser) and the server. They are especially useful in web applications for filtering, sorting, or passing data from one page to another.
In React JS, we can access query parameters using the useLocation hook from the react-router-dom package. Let's see how it works!
First, make sure you have React Router installed in your project. If not, install it using npm:
npm install react-router-domNow, let's create a simple example where we'll display a user's name passed via a query parameter.
import React from 'react';
import { useLocation } from 'react-router-dom';
function User() {
const location = useLocation();
const queryParams = new URLSearchParams(location.search);
const name = queryParams.get('name');
return (
<div>
<h1>Welcome, {name}</h1>
{/* Rest of the component */}
</div>
);
}
export default User;In the example above, we import useLocation and create a User functional component. We then use the URLSearchParams constructor to parse the query parameters from the current location's search property. Finally, we display the user's name by accessing it using the get() method.
Now, let's create a link that points to our User component with a query parameter.
import React from 'react';
import { Link } from 'react-router-dom';
function Navigation() {
return (
<nav>
<Link to={{ pathname: '/user', search: '?name=John' }}>View User</Link>
</nav>
);
}
export default Navigation;In the example above, we create a Navigation functional component that generates a link to our User component. We manually create the search property in the link's to object and set the user's name as "John" in this case.
What is the purpose of the `URLSearchParams` constructor in the given example?
To handle multiple query parameters, simply assign them to separate variables:
const queryParams = new URLSearchParams(location.search);
const name = queryParams.get('name');
const age = queryParams.get('age');It's essential to remember that query parameters must be URL encoded when passing them as part of a URL. For instance, if you want to pass a space-separated name like "John Doe", you'd need to URL encode it as "John+Doe".
When using Link components from React Router, you can pass query parameters as part of the link's to object:
<Link to={{ pathname: '/user', search: '?name=John+Doe&age=30' }}>View User</Link>How can you URL encode a space-separated name like "John Doe"?
That's it for our comprehensive guide on Query Parameters in React JS! Now you're ready to build dynamic and user-friendly web applications with ease. Happy coding! 🚀💻🌟