Skip to content
radicalbitPublic

About

No description, website, or topics provided.

Resources

Stars

12 stars

Watchers

3 watching

Forks

Repository files navigation

Formbit

Formbit is a lightweight React state form library designed to simplify form management within your applications. With Formbit, you can easily handle form state, validate user input, and submit data efficiently.

NPM license

Table of contents

Features

  • Intuitive and easy-to-use form state management.
  • Out of the box support for validation with yup.
  • Full TypeScript generics — useFormbit<FormData>(...) infers paths, values, and callbacks.
  • Support for handling complex forms with dynamic and nested fields via dot-path notation.
  • Context Provider for sharing form state across deeply nested component trees.
  • Seamless and flexible integration with React — works with Antd, MaterialUI, or plain HTML.

Install

yup, lodash and react are peer dependencies: install them alongside formbit.

npm install @radicalbit/formbit yup lodash
yarn add @radicalbit/formbit yup lodash

The hook is exported both as the default export and as the named export useFormbit. Bundlers (Vite, webpack, …) handle either. In plain Node ESM, or with TypeScript moduleResolution: node16/nodenext, use the named one:

import { useFormbit } from '@radicalbit/formbit';

Getting Started

Three steps: define a schema, call the hook, bind the UI.

import * as yup from 'yup';
import useFormbit from '@radicalbit/formbit';

// 1. Define a Yup schema and infer the TypeScript type from it
const schema = yup.object({
  name: yup.string().max(25, 'Max 25 characters').required('Name is required'),
  age:  yup.number().max(120, 'Must be 0–120').required('Age is required'),
});

type FormData = yup.InferType<typeof schema>;

const initialValues: Partial<FormData> = { name: undefined, age: undefined };

// 2. Call the hook with generics so every callback is fully typed
function Example() {
  const { form, submitForm, write, error, isDirty } = useFormbit<FormData>({
    initialValues,
    yup: schema,
  });

  const handleChangeName = ({ target: { value } }: React.ChangeEvent<HTMLInputElement>) => {
    write('name', value);
  };

  const handleChangeAge = ({ target: { value } }: React.ChangeEvent<HTMLInputElement>) => {
    write('age', Number(value));
  };

  const handleSubmit = () => {
    submitForm(
      ({ form }) => console.log('Validated form:', form),
      ({ errors }) => console.error('Validation errors:', errors),
    );
  };

  // 3. Bind inputs, errors, and submit — Formbit stays out of your UI
  return (
    <div>
      <label htmlFor="name">Name</label>
      <input
        id="name"
        type="text"
        value={form.name ?? ''}
        onChange={handleChangeName}
      />
      <div>{error('name')}</div>

      <label htmlFor="age">Age</label>
      <input
        id="age"
        type="number"
        value={form.age ?? ''}
        onChange={handleChangeAge}
      />
      <div>{error('age')}</div>

      <button disabled={!isDirty} onClick={handleSubmit} type="button">
        Submit
      </button>
    </div>
  );
}

export default Example;

Usage Patterns

Context Provider

Use FormbitContextProvider when you need to share form state across deeply nested components without prop drilling.

import { FormbitContextProvider, useFormbitContext } from '@radicalbit/formbit';
import * as yup from 'yup';

const schema = yup.object({
  name:    yup.string().required('Name is required'),
  surname: yup.string().required('Surname is required'),
  age:     yup.number().required('Age is required'),
});

type FormData = yup.InferType<typeof schema>;

const initialValues: Partial<FormData> = { name: undefined, surname: undefined, age: undefined };

// Wrap your form tree with the provider
function App() {
  return (
    <FormbitContextProvider<FormData>
      initialValues={initialValues}
      yup={schema}
    >
      <NameField />
      <SubmitButton />
    </FormbitContextProvider>
  );
}

// Any child can access form state without props
function NameField() {
  const { form, write, error } = useFormbitContext<FormData>();

  const handleChangeName = ({ target: { value } }: React.ChangeEvent<HTMLInputElement>) => {
    write('name', value);
  };

  return (
    <div>
      <input
        value={form.name ?? ''}
        onChange={handleChangeName}
      />
      <span>{error('name')}</span>
    </div>
  );
}

function SubmitButton() {
  const { submitForm, isDirty } = useFormbitContext<FormData>();

  return (
    <button
      disabled={!isDirty}
      onClick={() => submitForm(({ form }) => console.log(form))}
    >
      Submit
    </button>
  );
}

Edit / Initialize Pattern

Start with empty initial values and call initialize() once data arrives from an API.

import { useEffect, useState } from 'react';
import useFormbit from '@radicalbit/formbit';
import * as yup from 'yup';

const schema = yup.object({
  name:  yup.string().required(),
  email: yup.string().email().required(),
});

type FormData = yup.InferType<typeof schema>;

const initialValues: Partial<FormData> = { name: undefined, email: undefined };

function EditUserForm({ userId }: { userId: string }) {
  const { form, write, error, initialize, submitForm } = useFormbit<FormData>({
    initialValues,
    yup: schema,
  });

  const [loading, setLoading] = useState(true);

  // Fetch and initialize — resetForm() will revert to these values
  useEffect(() => {
    fetch(`/api/users/${userId}`)
      .then((res) => res.json())
      .then((user) => { initialize(user); setLoading(false); });
  }, [userId]);

  const handleChangeName = ({ target: { value } }: React.ChangeEvent<HTMLInputElement>) => {
    write('name', value);
  };

  const handleChangeEmail = ({ target: { value } }: React.ChangeEvent<HTMLInputElement>) => {
    write('email', value);
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    submitForm(({ form }) => console.log(form));
  };

  if (loading) return <p>Loading...</p>;

  return (
    <form onSubmit={handleSubmit}>
      <input value={form.name ?? ''} onChange={handleChangeName} />
      <div>{error('name')}</div>

      <input value={form.email ?? ''} onChange={handleChangeEmail} />
      <div>{error('email')}</div>

      <button type="submit">Save</button>
    </form>
  );
}

Multi-Step Form

Use __metadata to store step state and validateAll to gate navigation between steps.

import useFormbit from '@radicalbit/formbit';
import * as yup from 'yup';

const schema = yup.object({
  name:  yup.string().required('Name is required'),
  age:   yup.number().required('Age is required'),
  email: yup.string().email().required('Email is required'),
});

type FormData = yup.InferType<typeof schema>;

const initialValues: Partial<FormData> & { __metadata: { step: number } } = {
  name: undefined,
  age: undefined,
  email: undefined,
  __metadata: { step: 0 },
};

function MultiStepForm() {
  const { form, write, error, validateAll, submitForm } = useFormbit<FormData>({
    initialValues,
    yup: schema,
  });

  const step = (form.__metadata?.step as number) ?? 0;
  const goTo = (n: number) => write('__metadata.step', n);

  // Validate only the current step's fields before advancing
  const next = (paths: string[]) => {
    validateAll(paths, {
      successCallback: () => goTo(step + 1),
    });
  };

  const handleChangeName = ({ target: { value } }: React.ChangeEvent<HTMLInputElement>) => {
    write('name', value);
  };

  const handleChangeAge = ({ target: { value } }: React.ChangeEvent<HTMLInputElement>) => {
    write('age', Number(value));
  };

  const handleChangeEmail = ({ target: { value } }: React.ChangeEvent<HTMLInputElement>) => {
    write('email', value);
  };

  const handleSubmit = () => {
    submitForm(({ form }) => console.log('Submit:', form));
  };

  return (
    <div>
      {step === 0 && (
        <div>
          <input value={form.name ?? ''} onChange={handleChangeName} />
          <div>{error('name')}</div>
          <button onClick={() => next(['name'])}>Next</button>
        </div>
      )}

      {step === 1 && (
        <div>
          <input type="number" value={form.age ?? ''} onChange={handleChangeAge} />
          <div>{error('age')}</div>
          <button onClick={() => goTo(0)}>Back</button>
          <button onClick={() => next(['age'])}>Next</button>
        </div>
      )}

      {step === 2 && (
        <div>
          <input value={form.email ?? ''} onChange={handleChangeEmail} />
          <div>{error('email')}</div>
          <button onClick={() => goTo(1)}>Back</button>
          <button onClick={handleSubmit}>Submit</button>
        </div>
      )}
    </div>
  );
}

Silent Errors (Backend Errors)

Errors that do not come from the yup schema — typically a message returned by your backend — can be stored under the reserved silent key of errors. A silent error:

  • is written with setError('silent', message) and read with error('silent');
  • never goes through yup validation;
  • is ignored by isFormValid() and isFormInvalid(), so it does not disable your submit button;
  • survives write, validate and live validation of other fields;
  • is cleared by validateForm, submitForm (whether the form is valid or not), resetForm and initialize, so every new submit starts clean.

Nested paths work too, e.g. setError('silent.email', 'Already taken') and error('silent.email').

const { submitForm, error, isFormInvalid } = useFormbit<FormData>({ initialValues, yup: schema });

const handleSubmit = () => {
  submitForm(async ({ form }, setError, clearIsDirty) => {
    const response = await api.createUser(form);

    if (!response.ok) {
      setError('silent', response.message);
      return;
    }

    clearIsDirty();
  });
};

return (
  <>
    {error('silent') && <div role="alert">{error('silent')}</div>}
    <button disabled={isFormInvalid()} onClick={handleSubmit}>Submit</button>
  </>
);

Live Validation

A field that fails a validation becomes live-validated: from then on it is re-validated on every write, writeAll, remove and removeAll, so its error disappears as soon as the user fixes it. Check it with liveValidation(path); skip it for a single write with { noLiveValidation: true }. resetForm and initialize turn it off for every field.

Live validation is tied to the path, not to the value: if you remove a value and write it back, the path is still live-validated.

Arrays: the path includes the index, so live validation follows the index, not the item. If friends[1].name is live-validated and you drop the first row by writing a shorter array (e.g. write('friends', friends.filter((_, i) => i !== 0))), the invalid row moves to index 0 — which is not live-validated, so its error disappears until the next validate/submitForm — while friends[1].name stays live-validated on an index that no longer exists (and is silently skipped).

Local Development

For local development we suggest using Yalc to test your local version of formbit in your projects.

API Reference

FormbitObject

FormbitObject<T> = object

The object returned by useFormbit() and useFormbitContext(). Holds the form state and every method needed to read, mutate and validate the form.

Type Parameters

T

T extends FormbitValues

Properties

check

check: Check<Partial<T>>

Validates json against the current schema; returns the errors, or undefined if valid.

error

error: (path) => string | undefined

Returns the error message registered for path, if any.

Parameters
path

string

Returns

string | undefined

errors

errors: Errors

Error messages registered since the last validation, keyed by the value's dot-path.

Example
form:   { age: 1 }
errors: { age: "Age must be greater than 18" }
form

form: Partial<T>

The current form values. Partial: fields may be missing until validated.

initialize

initialize: Initialize<T>

Re-initializes the form with new initial values.

isDirty

isDirty: boolean

True once the user has interacted with the form.

isFormInvalid

isFormInvalid: () => boolean

True if any error is currently registered. Does not run validation.

Returns

boolean

isFormValid

isFormValid: () => boolean

True if no errors are currently registered. Does not run validation.

Returns

boolean

liveValidation

liveValidation: (path) => true | undefined

True if live-validation is active for path.

Parameters
path

string

Returns

true | undefined

remove

remove: Remove<T>

Removes the value at path, sets isDirty, then validates pathsToValidate plus every live-validated field.

removeAll

removeAll: RemoveAll<T>

Removes every given path, sets isDirty, then validates pathsToValidate plus every live-validated field.

resetForm

resetForm: () => void

Resets form, errors, liveValidation and isDirty back to their initial state.

Returns

void

setError

setError: SetError

Sets the error message at path; pass undefined to clear it.

setSchema

setSchema: SetSchema<T>

Replaces the current validation schema.

submitForm

submitForm: SubmitForm<T>

Validates the whole form and, if valid, runs the success callback to submit.

validate

validate: Validate<T>

Validates only path (ignores live-validated fields).

validateAll

validateAll: ValidateAll<T>

Validates only the given paths (ignores live-validated fields).

validateForm

validateForm: ValidateForm<Partial<T>>

Validates the whole form and registers any error.

write

write: Write<T>

Writes value at path, sets isDirty, then validates pathsToValidate plus every live-validated field.

writeAll

writeAll: WriteAll<T>

Writes every [path, value] pair, sets isDirty, then validates pathsToValidate plus every live-validated field.

Core Types

Errors

Errors = object

Error messages registered since the last validation, stored as a nested object that mirrors the shape of the form. Read a single message with error(path).

Index Signature

[key: string]: string | Errors | (string | Errors | undefined)[] | undefined

Example
form:   { age: 1, friends: [{ name: '' }] }
errors: { age: "Age must be greater than 18", friends: [{ name: "Name is required" }] }

FormbitValues

FormbitValues = Record<string, unknown> & object

Base shape of every form handled by formbit: an open record of values, plus an optional __metadata field formbit uses to carry data that must survive a reset/initialize but must NOT be submitted.

The generic T you pass to useFormbit<T>() must extend this type.

Type Declaration
__metadata?

optional __metadata?: Record<string, unknown>

FormState

FormState<T> = object

The whole internal state of the form (everything except the validation schema).

Type Parameters
T

T extends FormbitValues

Properties
errors

errors: Errors

form

form: T

initialValues

initialValues: T

isDirty

isDirty: boolean

liveValidation

liveValidation: LiveValidation

LiveValidation

LiveValidation = Record<string, true>

Fields currently under live-validation (re-validated on every form change). A field is added here automatically when it fails a validation. Empty by default.

Example
form:           { age: 1 }
liveValidation: { age: true }

Callback Types

CheckErrorCallback

CheckErrorCallback<T> = (json, inner, writer, setError) => void

Invoked by check() when the given json is invalid.

Type Parameters
T

T extends FormbitValues

Parameters
json

FormbitValues

inner

ValidationError[]

writer

FormState<T>

setError

SetError

Returns

void

CheckSuccessCallback

CheckSuccessCallback<T> = (json, writer, setError) => void

Invoked by check() when the given json is valid.

Type Parameters
T

T extends FormbitValues

Parameters
json

FormbitValues

writer

FormState<T>

setError

SetError

Returns

void

ErrorCallback

ErrorCallback<T> = (writer, setError) => void

Invoked by validation methods when validation fails.

Type Parameters
T

T extends FormbitValues

Parameters
writer

FormState<T>

setError

SetError

Returns

void

SubmitSuccessCallback

SubmitSuccessCallback<T> = (writer, setError, clearIsDirty) => void

Invoked by submitForm() once the whole form is valid — the place to send data to the backend. __metadata is stripped from writer.form before this runs.

Type Parameters
T

T extends FormbitValues

Parameters
writer

FormState<Omit<T, "__metadata">>

setError

SetError

clearIsDirty

() => void

Returns

void

SuccessCallback

SuccessCallback<T> = (writer, setError) => void

Invoked by validation methods when the form (or the validated paths) are valid.

Type Parameters
T

T extends FormbitValues

Parameters
writer

FormState<T>

setError

SetError

Returns

void

Method Types

Check

Check<T> = (json, options?) => ValidationError[] | undefined

See FormbitObject.check.

Type Parameters
T

T extends FormbitValues

Parameters
json

FormbitValues

options?

CheckFnOptions<T>

Returns

ValidationError[] | undefined

Initialize

Initialize<T> = (values) => void

See FormbitObject.initialize.

Type Parameters
T

T extends FormbitValues

Parameters
values

Partial<T>

Returns

void

Remove

Remove<T> = (path, options?) => void

See FormbitObject.remove.

Type Parameters
T

T extends FormbitValues

Parameters
path

string

options?

WriteFnOptions<T>

Returns

void

RemoveAll

RemoveAll<T> = (arr, options?) => void

See FormbitObject.removeAll.

Type Parameters
T

T extends FormbitValues

Parameters
arr

string[]

options?

WriteFnOptions<T>

Returns

void

SetError

SetError = (path, value) => void

See FormbitObject.setError.

Parameters
path

string

value

string | undefined

Returns

void

SetSchema

SetSchema<T> = (newSchema) => void

See FormbitObject.setSchema.

Type Parameters
T

T extends FormbitValues

Parameters
newSchema

ValidationSchema<T>

Returns

void

SubmitForm

SubmitForm<T> = (successCallback, errorCallback?, options?) => void

See FormbitObject.submitForm.

Type Parameters
T

T extends FormbitValues

Parameters
successCallback

SubmitSuccessCallback<T>

errorCallback?

ErrorCallback<Partial<T>>

options?

ValidateOptions

Returns

void

Validate

Validate<T> = (path, options?) => void

See FormbitObject.validate.

Type Parameters
T

T extends FormbitValues

Parameters
path

string

options?

ValidateFnOptions<T>

Returns

void

ValidateAll

ValidateAll<T> = (paths, options?) => void

See FormbitObject.validateAll.

Type Parameters
T

T extends FormbitValues

Parameters
paths

string[]

options?

ValidateFnOptions<T>

Returns

void

ValidateForm

ValidateForm<T> = (successCallback?, errorCallback?, options?) => void

See FormbitObject.validateForm.

Type Parameters
T

T extends FormbitValues

Parameters
successCallback?

SuccessCallback<T>

errorCallback?

ErrorCallback<T>

options?

ValidateOptions

Returns

void

Write

Write<T> = (path, value, options?) => void

See FormbitObject.write.

Type Parameters
T

T extends FormbitValues

Parameters
path

keyof T | string

value

unknown

options?

WriteFnOptions<T>

Returns

void

WriteAll

WriteAll<T> = (arr, options?) => void

See FormbitObject.writeAll.

Type Parameters
T

T extends FormbitValues

Parameters
arr

WriteAllValue<T>[]

options?

WriteFnOptions<T>

Returns

void

Options Types

CheckFnOptions

CheckFnOptions<T> = object

Options accepted by check().

Type Parameters
T

T extends FormbitValues

Properties
errorCallback?

optional errorCallback?: CheckErrorCallback<T>

options?

optional options?: ValidateOptions

successCallback?

optional successCallback?: CheckSuccessCallback<T>

ValidateFnOptions

ValidateFnOptions<T> = object

Options accepted by the validate methods.

Type Parameters
T

T extends FormbitValues

Properties
errorCallback?

optional errorCallback?: ErrorCallback<Partial<T>>

options?

optional options?: ValidateOptions

successCallback?

optional successCallback?: SuccessCallback<Partial<T>>

WriteAllValue

WriteAllValue<T> = [keyof T | string, unknown]

A single [path, value] pair accepted by writeAll.

Type Parameters
T

T extends FormbitValues

WriteFnOptions

WriteFnOptions<T> = object & ValidateFnOptions<T>

Options accepted by the write/remove methods (validate options plus path control).

Type Declaration
noLiveValidation?

optional noLiveValidation?: boolean

pathsToValidate?

optional pathsToValidate?: string[]

Type Parameters
T

T extends FormbitValues

Yup Re-Exports

ValidateOptions

ValidateOptions = YupValidateOptions

Options forwarded to yup's validation methods. See https://github.com/jquense/yup.

ValidationError

ValidationError = YupValidationError

The error object yup throws when a validation fails. See https://github.com/jquense/yup.

ValidationSchema

ValidationSchema<T> = ObjectSchema<T>

A validation schema built with yup.object(). See https://github.com/jquense/yup.

Type Parameters
T

T extends FormbitValues

License

MIT © [Radicalbit (https://github.com/radicalbit)]

About

No description, website, or topics provided.

Resources

Stars

12 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages