Skip to content

Instantly share code, notes, and snippets.

@ahallora
Last active February 3, 2024 21:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahallora/9fcbfc363e6c18a8cb67c53ceb716fa5 to your computer and use it in GitHub Desktop.
Save ahallora/9fcbfc363e6c18a8cb67c53ceb716fa5 to your computer and use it in GitHub Desktop.
React form where form state is saved in querystring using react-hook-form
"use client";
import { useForm } from "react-hook-form";
import { useEffect } from "react";
const AdvancedForm = () => {
const { register, handleSubmit, setValue, watch } = useForm();
const watchedValues = watch();
// Function to update the query string
const updateQueryString = () => {
const queryString = new URLSearchParams(watchedValues).toString();
window.history.pushState(null, "", `?${queryString}`);
};
const onSubmit = (data) => {
updateQueryString();
console.log(data);
};
// Set form values from query string on component mount
useEffect(() => {
const queryValues = Object.fromEntries(
new URLSearchParams(window.location.search.split(/\?/)[1])
);
for (const [key, value] of Object.entries(queryValues)) {
if (value.toLowerCase() === "false") {
setValue(key, false);
continue;
}
if (value.toLowerCase() === "true") {
setValue(key, true);
continue;
}
setValue(key, value);
}
}, []);
// Update query string on form value change
useEffect(() => {
updateQueryString();
}, [watchedValues]);
return (
<form onSubmit={handleSubmit(onSubmit)} method="get" action="/">
<input {...register("input1")} type="text" />
<select {...register("select1")}>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
<input {...register("checkbox1")} type="checkbox" />
<input {...register("range1")} type="range" />
<button type="submit">Submit</button>
</form>
);
};
export default AdvancedForm;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment