Query Parameters
In this guide, you’ll learn how to access and set query parameters in a Hilla view using React.
Using Query Parameters
To work with query parameters in Hilla views, you can use the useSearchParams hook from react-router. This hook provides methods to read, update, and delete query parameters without causing a full page reload.
The useSearchParams hook returns an array with two elements:
-
searchParams— aURLSearchParamsobject for reading parameters. -
setSearchParams— a function to update or clear query parameters.
Here’s an example of a view that manages a search term using query parameters:
Source code
tsx
import { useSearchParams } from 'react-router';
import { TextField } from '@vaadin/react-components/TextField.js';
export default function ProductView() {
const [searchParams, setSearchParams] = useSearchParams();
const searchTerm = searchParams.get('category') || '';
return (
<div>
<TextField
label="Search for:"
value={searchTerm}
onValueChanged={(e) => {
const newValue = e.detail.value;
if (newValue) {
setSearchParams({ category: newValue });
} else {
setSearchParams({});
}
}}
/>
<div>Current search term: {searchTerm}</div>
</div>
);
}In this example, the category parameter is used to store the search term. When a user types a new value, setSearchParams updates the query parameter accordingly. If the value is empty, passing an empty object to setSearchParams clears all query parameters.
Multiple Query Parameters
You can work with multiple query parameters simultaneously. In the following example, a view manages both a search filter (category) and a sorting order (sort) while ensuring any other query parameters are preserved when updating values:
Source code
tsx
import { useSearchParams } from 'react-router';
import { TextField } from '@vaadin/react-components/TextField.js';
import { Select } from "@vaadin/react-components";
export default function ProductView() {
const [searchParams, setSearchParams] = useSearchParams();
const category = searchParams.get('category') || '';
const sortOrder = searchParams.get('sort') || 'asc';
// Function to update query parameters while preserving existing ones
const updateParams = (params: Record<string, string>) => {
setSearchParams({
...Object.fromEntries(searchParams),
...params
});
};
// Ensure URL parameters reflect the current state
if (category !== searchParams.get('category')
|| sortOrder !== searchParams.get('sort')) {
updateParams({ category: category, sort: sortOrder });
}
return (
<div>
<TextField
label="Search for:"
value={category}
onValueChanged={(e) => updateParams({ category: e.detail.value })}
/>
<Select
label="Sort order:"
value={sortOrder}
items={[
{ label: 'Ascending', value: 'asc' },
{ label: 'Descending', value: 'desc' },
]}
onValueChanged={(e) => updateParams({ sort: e.detail.value })}
/>
<div>Current search term: {category}</div>
<div>Current sort order: {sortOrder}</div>
</div>
);
}In this example:
-
The
categoryandsortparameters are managed together in the query string. -
The
updateParamsfunction ensures that only the changed parameter is updated while preserving any other existing parameters. -
The URL parameters are updated dynamically to reflect changes in search input and sorting selection.
Query Parameters Best Practices
When working with query parameters in Hilla, follow these best practices:
-
Default Values: Determine default values when parameters are missing:
Source code
tsx
const page = parseInt(searchParams.get('page') || '1'); const size = parseInt(searchParams.get('size') || '10'); -
Type Safety: Convert string parameters to appropriate types:
Source code
tsx
const isActive = searchParams.get('active') === 'true'; const count = Number(searchParams.get('count')); -
URL Length: Keep URLs manageable by using concise parameter names and avoiding unnecessary parameters. Extremely long URLs cannot work across all browsers or cannot be handled by all servers.
-
State Management: Use query parameters for shareable state that should persist across page reloads.
-
Security Awareness: Remember that query parameters are visible in the URL and should not contain sensitive information. Thus, never include sensitive data such as security tokens as query parameters, but use HTTP headers (e.g., authorization header), or request body of the post request, or store them in secure cookies.