New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More

@codemask-labs/forms

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@codemask-labs/forms

`codemask-labs/forms` is a continuation of old `react-form-builder-v2` package. Currenctly in **alpha** due to breaking changes and testing.

1.0.11-beta
latest
Version published
Maintainers
0
Created

codemask-labs/forms

codemask-labs/forms is a continuation of old react-form-builder-v2 package. Currenctly in alpha due to breaking changes and testing.

New features:

  • less code
  • less re-renders
  • zod schemas for validation
  • uses stan-js underneath

Basic usage

  • Start with schema definition. It can be placed inline or in separate file (as a hook):
import z from 'zod'

const useOTPFormSchema = () => {
   const phoneNumber = z
      .string()
      // chain your validation logic
      .length(9, {
         // override default zod validation messages
         message: 'Phone number must have 9 digits'
      })
      .default('')

   const otpCode = z
     .string()
     .optional() // mark field as optional
     .default('123456') // set default values eg. when you want to prefill the form, must be called at the end of the chain

   return {
       phoneNumber,
       otpCode
   }
}
  • Define useForm:
const App = () => {
    const { form, submit, isValid } = useForm({
        fields: useOTPFormSchema(),
        onSuccess: ({ phoneNumber, otpCode }) => {
           // form is valid!
        },
        onError: errors => {
           // form is invalid!
        }
    })

    return (
        <form
            onSubmit={event => {
                event.preventDefault()
                submit()
            }}
        >
            <Input field={form.name} />
            <Input field={form.email} />
            <button disabled={!isValid}>
                Submit
            </button>
        </form>
    )
}
  • Pass field to your form components:
const Input: React.FunctionComponent<{ field: ReactiveFormField<string> }> = ({ field: useField }) => {
    const { value, onChange, reset, error, validate } = useField()

    return (
        <div>
            <input
                 value={value}
                 onChange={event => onChange(event.target.value)}
                 onBlur={() => validate()}
             />
            <span>{error}</span>
            <button
                type='button'
                onClick={reset}
             >
                  Reset
            </button>
        </div>
    )
}

[!WARNING]
If you use React Compiler, make sure you rename field to useField - otherwise entire hook will be memoized and won't update the state

API

useForm

proptypefunctionality
formRecord<string, ReactiveFormField<any>>all fields that should be passed to corresponding components
submit() => voidSubmit the form
reset(...args?: Array<string>) => voidresets either entire form or specific fields
getValues() => Record<string, any>Returns your form values as object
isValidbooleanDefines if your form is valid
updateForm(fields: Partial<Record<string, Partial<FormField<any>>>) => voidstanjs method to update form state
useFormEffect(fields: Record<string, any>) => voidstanjs effect - function that allows to subscribe to store's values change

useForm config

proptypefunctionality
fieldsRecord<string, ZodDefault<any>>zod based schema for your form
onSuccess(fields: Record<string, any>) => voidcalled when your form is valid
onError(errors: Record<string, string>) => voidcalled when form is not valid, returns a pair for field key and error message
onSubmit(fields: Record<string, any>) => voidcalled after the validation, but before onSuccess or onError, useful for additonal validation like dependent fields

field (ReactiveFormField<any>>)

proptypefunctionality
errorstringfield error message passed from zod
hasErrorbooleandefines if your field has error
valueanycurrent field value
onChange(value: any) => voidfunction to update current field value
reset() => voidresets current field to defaults
validate() => voidshould be called to validate the field eg. onBlur event

Notes

If you want to dynamically set field as optional you can either conditionally return different schemas, or create yourself simple util to do this:

export const dynamicOptional = <TSchema extends z.ZodDefault<z.ZodTypeAny>>(schema: TSchema, optional?: boolean) =>
    optional ? schema.optional().default(schema._def.defaultValue()) : schema

FAQs

Package last updated on 10 Feb 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts