Introduction
In today's digital age, the usage of URLs as a medium to share the state of the application is growing rapidly. This has become especially popular in web applications, where the user's actions can be replicated by simply sharing a URL. This article will introduce you to an efficient way of parsing URL search parameters with the use of Zod library and demonstrate how they can be used in a React form.
What is Zod?
Zod is a schema declaration and validation library for JavaScript and TypeScript. It can be used to create a "blueprint" or "schema" for JavaScript objects, ensuring that the data you're working with meets certain criteria before it's processed by your application. With the use of Zod, you can parse URL search parameters accurately and efficiently, and validate the data before it enters your system.
Parsing Parameters with Zod
Before we jump into parsing parameters with Zod, let's first install the library using npm. Open your terminal and navigate to your project directory. Run the following command to install Zod:
npm install zod
Now, let's dive into the code example to understand how to parse URL parameters using Zod.
The first part of the code defines a constant object named allowedValues
, which consists of two properties, periods
and posts
. These properties are an array of strings that represent the allowed values for the corresponding search parameters.
const allowedValues = {
periods: ['1', '3', '6', '12'],
posts: ['10', '25', '50'],
} as const;
Next, we define a schema ParamsSchema
using Zod. This schema reflects the structure of our search parameters. We expect three parameters: tags
, period
, and posts
. The tags
parameter is expected to be a string, while period
and posts
parameters are expected to be one of the allowed values defined earlier. If these parameters are not present in the URL, we provide default values using the catch
method.
import { z } from "zod";
const ParamsSchema = z.object({
tags: z.string().catch(''),
period: z.enum(allowedValues.periods).catch(allowedValues.periods[0]),
posts: z.enum(allowedValues.posts).catch(allowedValues.posts[0]),
});
Finally, we create an instance of URLSearchParams
with the current URL's search string and parse the search parameters using our schema.
const searchParams = new URLSearchParams(window.location.search);
const params = ParamsSchema.parse({
tags: searchParams.get('tags'),
period: searchParams.get('period'),
posts: searchParams.get('posts'),
});
This way, Zod helps us parse the search parameters from the URL and validates them against the defined schema. If the validation fails, Zod throws an error, which can be caught and handled accordingly.
Using Parsed Parameters in Form
After parsing URL parameters with Zod and validating them, you can use these values to set the initial state in your React components, for example, to set initial filters in a form.
Consider the following code example. Here, we have a React component named App
, which consists of a form with two select inputs and a text input. These inputs correspond to the period
, posts
, and tags
parameters we parsed from the URL.
export const App = () => {
return (
<form>
<input
type="text"
name="tags"
defaultValue={params.tags}
placeholder="javascript, react"
/>
<select name="period" defaultValue={params.period}>
{allowedValues.periods.map((period, index) => (
<option key={`period-${index}`} value={period}>
{period}
</option>
))}
</select>
<select name="posts" defaultValue={params.posts}>
{allowedValues.posts.map((post, index) => (
<option key={`post-${index}`} value={post}>
{post}
</option>
))}
</select>
<button>Submit</button>
</form>
);
};
In this code, we are setting the defaultValue
attribute of each input to the corresponding parameter value from the URL. This way, when a user accesses the page with specific URL parameters, the form fields will be pre-filled with those values.
The map
function is used to generate the options for the select inputs based on the allowedValues
we defined earlier. Each option's value is set to the corresponding value from the allowedValues
array, and the text inside the option tag is also set to the same value.
This approach allows you to create a seamless user experience, where the state of the form is linked with the URL parameters. This can be particularly useful for sharing links with pre-set filters or settings.
Summary
In conclusion, parsing and syncing URL search parameters with React state is a powerful way of enhancing user experience, making your application more interactive, and replicating a specific state of the app through a simple URL.
You can check out the full code for this tutorial below:
I hope you found this article helpful. If you have any questions or thoughts about this topic, please feel free to leave a comment below or contact me on Twitter. I'd love to hear your feedback.
Thanks for reading! 👋
Top comments (1)
i've written a library to help with this. instead of manually building up an object using
searchParams.get
, it uses the zod schema to do it. handles arrays and any other data type you throw at it.project:
github.com/schpet/zod-urlsearchparams