use-form-field
An unopionated react form context library using hooks and the context API.
Install
npm install use-form-field
Documentation
useFormField
;
Options
name
- string name to use for the form field.
controlled
- boolean optional Whether field is going to be controlled or not. Ultimately this will assume you are using
the ref as opposed to the value and not trigger a re-render on value changes.
Example
import useFormField from "use-form-field"; const UncontrolledInput = name const set ref error = ; const handleChange = { ; }; return <React.Fragment> <input = ="text" = = /> error </React.Fragment> ;;
useForm
;
Options
withValues
- boolean optional Whether to return complete values object. This will cause re-renders on change
onChange
- function optional Function containing object of changed values.
Example
import useForm from "use-form-field"; const Form = const get isValid = ; const values setValues = ; const handleSubmit = { e; ; }; return <React.Fragment> <form => <UncontrolledInput ="field" /> <br /> <button ="submit" => Submit </button> </form> values && JSON </React.Fragment> ;;
FormProvider
<FormProvider />
Options
values
- object optional An object containing values to set field values to.
schema
- object optional A yup compatible schema for automatic validation
children
- Children can be React elements or a function, if using a function you will receive the return value from useForm() and you may pass additional props to FormProvider that will be used as arguments for useForm().
Example (JSX)
import FormProvider from "use-form-field"; const App = <FormProvider> <Form /> </FormProvider>;
Example (Function)
import FormProvider from "use-form-field"; const App = <FormProvider > values isValid <React.Fragment> <Form /> JSON " " isValid ? "valid" : "invalid" </React.Fragment> </FormProvider>;
Full example with dynamic fields
import FormProvider useForm useFormField from "use-form-field";import object string from "yup"; const initialValues = field1: "field 1" field2: "field 2";const validationSchema = ; const ControlledInput = name const set value error = ; const handleChange = { ; }; return <React.Fragment> <input = ="text" = = /> error </React.Fragment> ;; const UncontrolledInput = name const set ref error = ; const handleChange = { ; }; return <React.Fragment> <input = ="text" = = /> error </React.Fragment> ;; const Form = const get isValid = ; const values setValues = ; const fields setFields = ; const handleSubmit = { e; ; }; const handleFlip = ; ; return <React.Fragment> <form => <ControlledInput = /> <br /> <UncontrolledInput = /> <br /> <button ="button" => Flip </button> <button ="submit" => Submit </button> </form> values && JSON </React.Fragment> ;; const App = <FormProvider = => <Form /> </FormProvider>;