Skip to Content
FrontendBundlesCRUDHooksuseScrollToError

useScrollToError

useScrollToError automatically scrolls the page to the first field with a validation error when form submission fails. Improves UX for long forms.


Import

import { useScrollToError } from "@phpcreation/frontend-crud-react-nextjs-bundle/hooks/useScrollToError";

Usage

import { useForm } from "react-hook-form"; import { useScrollToError } from "..."; function LongForm({ schema }) { const form = useForm({ resolver: zodResolver(schema) }); useScrollToError(form); const onSubmit = form.handleSubmit((data) => { // submit logic }); return ( <form onSubmit={onSubmit}> <RenderFormFields fields={formFields} form={form} /> </form> ); }

How It Works

On each form.formState.errors change (after a failed submit attempt), the hook finds the first field element with an error and smoothly scrolls it into view.


Last updated on