Formular
Easy way to work with forms in React. Using React Hooks 😏
Features
- Just 3kb gzip.
- React hooks included.
- Easy way to start work with forms in React in 2 steps: install and use it 😎.
- Changes made within form rerender only changed fields not everything unlike in most other form libs.
Quick start
Installation
npm install formular
Usage
import { useForm } from 'formular'
import { Input } from 'formular/lib/tags'
const App = () => {
const form = useForm({
fields: {
email: [ required ],
password: [ required ],
},
})
const handleSubmit = useCallback(() => {
form.submit()
.then((values) => {
}, (errors) => {
})
}, [])
return (
<Fragment>
<Input field={form.fields.email} />
<button onClick={handleSubmit}>Submit</button>
</Fragment>
)
}
Or if you need only one field you can just do
import { useField } from 'formular'
import { Input } from 'formular/lib/tags'
const App = () => {
const field = useField({
validate: [ required ],
})
const handleSubmit = useCallback(() => {
form.validate()
.then((error) => {
})
}, [])
return (
<Fragment>
<Input field={field} />
<button onClick={handleSubmit}>Submit</button>
</Fragment>
)
}
Field validation
const required = (value) => !value && value !== 0 ? 'Required' : undefined
Examples
Options
Form
type FormOpts = {
name?: string
fields: {
[key: string]: FieldOpts
}
initialValues?: object
}
Field
type FieldOpts = {
name?: string
value?: string
validate?: Array<Function>
readOnly?: boolean
validationDelay?: number
}
Interfaces
Form
type FormEntity = {
name?: string
opts: FormOpts
fields: {
[key: string]: Field
}
state: {
isValid: boolean
isChanged: boolean
isValidating: boolean
isSubmitting: boolean
isSubmitted: boolean
}
setState(values: Partial<State>): void
setValues(values: object): void
getValues(): object
unsetValues(): void
getErrors(): object
async validate(): Promise<boolean>
async submit(): Promise<object>
on(eventName: string, handler: Function): void
off(eventName: string, handler: Function): void
}
const form: FormEntity = useForm(opts)
Field
type FieldEntity = {
form?: Form
name?: string
opts: FieldOpts
node?: HTMLElement
validators: Array<Function>
readOnly: boolean
debounceValidate: Function
state: {
value: any
error: any
isChanged: boolean
isValidating: boolean
isValidated: boolean
isValid: boolean
}
setState(values: Partial<State>): void
setRef(node: HTMLElement): void
unsetRef(): void
set(value: any): void
unset(): void
validate = (): CancelablePromise
on(eventName: string, handler: Function): void
off(eventName: string, handler: Function): void
}
const field: FieldEntity = useField(opts)
Events
Form
form.on('state change', (state) => {
})
form.on('change', (field) => {
})
form.on('blur', (field) => {
})
Field
form.on('state change', (state) => {
})
field.on('set', (value) => {
})
field.on('change', (value) => {
})
field.on('unset', () => {
})
field.on('start validate', () => {
})
field.on('validate', (error) => {
})
field.on('blur', () => {
})