JSPM

react-use-simple-form

1.0.2
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 1
  • Score
    100M100P100Q31324F
  • License MIT

A React hook which manages and validates form state.

Package Exports

  • react-use-simple-form
  • react-use-simple-form/dist/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (react-use-simple-form) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme


useSimpleForm()

Bundlephobia Types NPM Version MIT License

npm i react-use-simple-form

Manage the state for simple forms in a flexible and un-opinionated way. This library has no UI components, and only simplifies the management of state and validation.

Quick Start

Create your custom hook to manage your state

import { useSimpleForm, SimpleFormValidators } from "react-use-simple-form";

// Specify the type of your state
type State = {
    name: string,
    age: number,
};

// and the initial state
const initialState: State = {
    name: '',
    age: 0,
}

// and optionally, validators
const validators: SimpleFormValidators<State> = {
    name: /^[a-zA-Z- ]{2,50}$/, // you can specify a regex
    age: (ageToValidate, entireForm) => ageToValidate >= 25 && ageToValidate < 90, // or a function
    // fields without validators specified will be assumed to be valid
}


export const ExampleComponent: React.FC = () => {
    const myForm = useSimpleForm(initialState, validators)
    console.log(myForm)
    return (
        <div>
            <label>Name</label>
            <input
                id={'name-input'}
                className={ myForm.manager.name.isValid ? 'valid' : 'invalid' }
                type={'text'}
                value={myForm.manager.name.value}
                onChange={(e) => myForm.manager.name.set(e.target.value)}
            />

            <label>Age</label>
            <input
                className={ myForm.manager.age.isValid ? 'valid' : 'invalid' }
                type={'number'}
                step={1}
                min={0}
                max={100}
                value={myForm.manager.age.value}
                onChange={(e) => myForm.manager.age.set(parseFloat(e.target.value))}
            />

            <button disabled={!myForm.isValid} onClick={() => {}}>
                Submit
            </button>

            <button onClick={() => myForm.set(initialState)}>
                Reset
            </button>
        </div>
    );
};