Form persistence for browser applications
npm install @ryanflorence/persist-formBrings the browser's default HTML form value persistence to client side rendering with both a Custom Element or a React Hook.
``bash`
npm install @ryanflorence/persist-form
First register the custom element:
`ts`
import "@ryanflorence/persist-form/html";
Then render it inside a form.
`html`
If no key is given, window.location.pathname is used.
Full copy/paste example
`html
`
With React 19 you can use a ref:
`tsx
import { usePersistedForm } from "@ryanflorence/persist-form/react";
function MyForm() {
let { persistFormRef } = usePersistedForm();
return (
Or use the hooks for more control (and if you're on React 18):
`tsx
import { usePersistedForm } from "@ryanflorence/persist-form/react";function MyForm() {
const { persist, restore, clear } = usePersistedForm();
return (
// restore when the form mounts
ref={node => node && restore(node)}
// persist on change of form elements
onChange={e => persist(e.currentTarget)}
// clear after submission
onSubmit={e => {
e.preventDefault();
clear();
}}
>
{/ form fields /}
);
}
`#### Custom Key
By default the
location.key is used, but you can provide a custom key.`tsx
// not attached to locations
usePersistedForm("login-form");// use the URL instead of location.key
usePersistedForm(location.pathname);
`$3
Integrate with any setup:
`ts
import { persist, restore, clear } from "@ryanflorence/persist-form";// Save form state
let form = document.querySelector("form");
persist("my-form", form);
// Restore form state
restore("my-form", form);
// Clear saved state
clear("my-form");
// Example with event handlers
form.addEventListener("change", () => {
persist("my-form", form);
});
document.addEventListener("DOMContentLoaded", () => {
restore("my-form", form);
});
``- Uses sessionStorage, so form data persists only for the current browser session
- For React Router integration, form data is keyed by location.key, so the same form can be persisted with different data across the history stack
- Handles all form input types including text fields, checkboxes, radio buttons, etc. (Files aren't supported due to browser limitations)
MIT