1.4.0 • Published 4 years ago

form-hooks-light v1.4.0

Weekly downloads
2
License
MIT
Repository
github
Last release
4 years ago

Formook

Lightweight hooks to deal with React forms

npm i form-hooks-light --save

API

Sets a state for an object, with a generic type-safe setter

useFormState: <T extends object>(object?: T) => [formState, setFormState];

Validation schema are made using a mix of Yup (https://github.com/jquense/yup) and boolean validation functions

(object: T) => boolean;

Validation will be triggered only when the object is updated

useFormValidation: <T extends object>(
  schema: FormValidationSchema<T>,
  object: T
) => {
  canValidate: boolean;
  errors: FormValidationError < T > [];
};

Example

interface Test {
  foo: string;
  foo2: number;
}

const schema: FormValidationSchema<Test> = {
  foo: (object: Test) => foo.length > 5,
  foo2: Yup.number.max(10),
};

Tool for selects

FormSelectItem supports common format ({ value, label }) and specific SemanticUI format ({ key, value, text })

useFormSelect<T extends object>(
  objects: T[],
  format: (object: T) => FormSelectItem,
  defaultItem?: T
): {
  suggestions: FormSelectItem[];
  onSelect: (object: T) => void;
  onClear: () => void;
  itemSelected: FormSelectItem | undefined;
  objectSelected: T | undefined;
};

Solution for many selects in a single component

FormSelectComponent<T extends object>(
  id?: string;
  render: (values: FormSelect<T>) => JSX.Element;
  objects: T[];
  format: (object: T) => FormSelectItem;
  formSelectStore?: FormSelectComponentStore<T>;
  defaultItem?: T;
): JSX.Element

export function useFormSelectStore<
  T extends object
>(): {
  get: (key: string) => FormSelect<T>;
  store: (key: string, values: FormSelect<T>) => void;
}

Example

const App = () => {
  const formSelectStore = useFormSelectStore();
  const { objectSelected, onSelect, onClear } = formSelectStore.get("id");

  return (
    <FormSelectComponent
      id="id"
      objects={[
        {
          foo: "foo",
        },
      ]}
      format={() => ({
        value: "foo",
        label: "foo",
      })}
      render={() => <>foo</>}
      formSelectStore={formSelectStore}
    />
  );
};
1.4.0

4 years ago

1.3.7

4 years ago

1.3.6

4 years ago

1.3.5

4 years ago

1.3.4

4 years ago

1.3.3

4 years ago

1.3.2

4 years ago

1.3.1

4 years ago

1.3.0

4 years ago

1.2.7

4 years ago

1.2.6

4 years ago

1.2.5

4 years ago

1.2.4

4 years ago

1.2.3

4 years ago

1.2.0

4 years ago

1.2.2

4 years ago

1.2.1

4 years ago

1.0.10

4 years ago

1.0.9

4 years ago

1.0.8

4 years ago

1.0.7

4 years ago

1.0.6

4 years ago

1.0.5

4 years ago

1.0.4

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago