formhero/README.md

455 lines
11 KiB
Markdown
Raw Normal View History

2019-10-19 06:47:15 +00:00
![Logo](https://raw.githubusercontent.com/cupcakearmy/formhero/master/.github/Logo.jpg)
2019-09-26 19:30:28 +00:00
2019-09-26 20:05:53 +00:00
![Version](https://badgen.net/npm/v/formhero)
![Dependencies](https://badgen.net/david/dep/cupcakearmy/formhero)
![Size Badge](https://badgen.net/bundlephobia/minzip/formhero)
2019-09-26 20:40:37 +00:00
**Fully customisable react form utility.**
2019-09-26 20:05:53 +00:00
2019-09-26 20:06:16 +00:00
## 🌈 Features
2019-09-26 19:30:28 +00:00
- Typescript compatible
- Customizable extractor, validator, getter and setters. (More in the docs)
2019-09-27 12:34:58 +00:00
- **0** Dependencies
2019-10-09 14:03:08 +00:00
- Tiny **~0.7kB**
2019-09-26 20:57:36 +00:00
- React Hooks
2019-09-26 19:30:28 +00:00
2019-10-09 13:57:02 +00:00
###### Installation
```
npm i formhero
```
### 👁 Demos
2019-09-28 17:30:04 +00:00
2019-10-19 06:45:14 +00:00
- [**_Live Web_**](https://cupcakearmy.github.io/formhero/)
- [**_Live Codesandbox_**](https://codesandbox.io/embed/formhero-simple-bdcx2?expanddevtools=1&fontsize=14)
- [**_Live React-Native_**](https://snack.expo.io/@cupcakearmy/useform)
2019-10-09 13:55:46 +00:00
2019-10-09 13:57:02 +00:00
### Links
2019-10-09 13:55:46 +00:00
2019-09-28 18:06:29 +00:00
- [Examples](#-examples-more-here)
2019-09-28 17:31:10 +00:00
- [Docs](#-documentation)
2019-09-28 17:30:04 +00:00
- Contructor
2019-09-28 17:31:10 +00:00
- [Initial State](#initial)
- [Validators](#validators)
2019-09-28 18:02:45 +00:00
- [Options](#options)
2019-09-28 17:30:04 +00:00
- Returns
2019-10-19 06:45:14 +00:00
- [field](#field)
2019-09-28 17:31:10 +00:00
- [form](#form)
- [errors](#errors)
- [isValid](#isvalid)
2019-10-19 14:56:43 +00:00
- [setField](#setfield)
- [setForm](#setform)
- [setErrors](#seterrors)
2019-09-28 17:30:04 +00:00
2019-10-18 12:52:37 +00:00
## 🤔 Motivation
2019-10-19 06:45:14 +00:00
So why write yet another form utility you might ask? First off, I don't like the Formik approach. In my humble opition formik is very verbose and requires lots of boilerplate. Also does not work with hooks. [react-hook-form](https://react-hook-form.com/) is a very cool library and it is the main inspiration for formhero. It does almost everything right... typescript, no deps, small, concise.
2019-10-18 12:54:42 +00:00
The problem that I found while using it was that 3rd party ui libs like [Ant Design](https://ant.design/) or [Fabric UI](https://developer.microsoft.com/en-us/fabric#/controls/web) do not always have the standart `onChange` or `value` props in their components. That is where react-hook-form starts falling apart. This is what formhero tries to address in the most minimalistic way possible, with as little code as needed. All in pure typescript and no deps.
2019-09-27 12:33:51 +00:00
2019-09-26 19:30:28 +00:00
## 🚀 Quickstart
2019-09-26 19:31:13 +00:00
```typescript
2019-09-26 19:30:28 +00:00
import ReactDOM from 'react-dom'
import { useForm } from 'formhero'
2019-09-27 12:33:15 +00:00
const Form = () => {
2019-10-19 06:45:14 +00:00
const { field, form } = useForm({
2019-09-27 12:33:15 +00:00
username: '',
password: '',
})
const _submit = (e: React.FormEvent) => {
e.preventDefault()
console.log(form)
}
return (
<div>
<form onSubmit={_submit}>
2019-10-19 06:45:14 +00:00
<input {...field('username')} />
<input {...field('password')} />
2019-09-27 12:33:15 +00:00
<button type="submit">Go 🚀</button>
</form>
</div>
)
}
```
2019-09-28 18:06:29 +00:00
## 🔥 Examples [(More Here)](https://github.com/CupCakeArmy/formhero/tree/master/examples)
2019-09-28 18:04:34 +00:00
2019-09-28 17:14:40 +00:00
### Validation
2019-09-27 12:33:15 +00:00
```typescript
2019-09-28 17:14:40 +00:00
const Form = () => {
2019-10-19 06:45:14 +00:00
const { field, form, errors } = useForm(
{
username: '',
email: '',
password: '',
2019-09-28 17:16:45 +00:00
},
2019-10-19 06:45:14 +00:00
{
username: value => value.length > 3,
email: {
validator: /@/,
message: 'Must contain an @',
2019-09-28 17:16:45 +00:00
},
2019-10-19 06:45:14 +00:00
password: [
{
validator: /[A-Z]/,
message: 'Must contain an uppercase letter',
},
{
validator: /[\d]/,
message: 'Must contain a digit',
},
],
}
)
2019-09-28 17:16:45 +00:00
return (
<form>
<h1>Errors & Validation</h1>
2019-10-19 06:45:14 +00:00
<input {...field('username')} placeholder="Username" />
2019-09-28 17:16:45 +00:00
{errors.username && 'Must be longer than 3'}
2019-10-19 06:45:14 +00:00
<input {...field('email')} placeholder="EMail" />
2019-09-28 17:16:45 +00:00
{errors.email}
2019-10-19 06:45:14 +00:00
<input {...field('password')} placeholder="Password" type="password" />
2019-09-28 17:16:45 +00:00
{errors.password}
</form>
)
2019-09-28 17:14:40 +00:00
}
```
2019-09-27 12:33:15 +00:00
2019-09-28 17:14:40 +00:00
### Easy Customization
Often it happens that you use a specific input or framework, so the default getter, setter and extractor for the event won't cut it. No worries: formhero got you covered!
```typescript
2019-09-26 19:30:28 +00:00
const Form = () => {
2019-10-19 06:45:14 +00:00
const { field, form, errors } = useForm({
2019-09-28 17:16:45 +00:00
awesome: true,
})
2019-09-26 19:30:28 +00:00
2019-09-28 17:16:45 +00:00
return (
2019-10-19 06:45:14 +00:00
<form
onSubmit={e => {
e.preventDefault()
console.log(form)
}}
>
2019-09-28 17:16:45 +00:00
<h1>Custom</h1>
2019-09-26 19:30:28 +00:00
2019-09-28 17:16:45 +00:00
<label>
2019-10-19 06:45:14 +00:00
<input
type="checkbox"
{...field('awesome', {
setter: 'checked',
getter: 'onChange',
extractor: e => e.target.checked,
})}
/>
2019-09-28 17:16:45 +00:00
Is it awesome?
2019-10-19 06:45:14 +00:00
</label>
2019-09-26 19:30:28 +00:00
2019-09-28 17:16:45 +00:00
<input type="submit" />
</form>
)
2019-09-26 19:30:28 +00:00
}
```
2019-10-25 08:58:00 +00:00
### Dynamic Fields
Sometimes you don't know all the fields upfront. You can simply define a generic type and assign it to the initial object. Of course type assistance is limited in this case as formhero cannot be sure what keys are valid.
```typescript
import React from "react";
import ReactDOM from "react-dom";
import { useForm } from "formhero";
type MyForm = { [field: string]: string | number };
const init: MyForm = {
username: "unicorn",
password: ""
};
const Form: React.FC = () => {
const { field, form, errors } = useForm(init);
return (
<form>
<input {...field("username")} placeholder="Username" />
<input {...field("someother")} placeholder="Something else" />
<input {...field("password")} placeholder="Password" type="password" />
</form>
);
};
```
2019-09-28 17:30:04 +00:00
## 📖 Documentation
2019-09-26 19:30:28 +00:00
### `useForm`
```typescript
2019-10-19 06:45:14 +00:00
const { field, errors, update, form, isValid } = useForm(initial, validators, options)
2019-09-26 19:30:28 +00:00
```
2019-09-26 20:53:43 +00:00
### Initial
This is the base state of the form. Also the typescript types are inhered by this.
###### Example
```javascript
const initial = {
username: 'defaultValue',
password: '',
rememberMe: true,
}
```
### Validators
2019-10-19 18:15:18 +00:00
A validator is an object that taked in either a `RegExp` or a `Function` (can be async) or an array of those. Optionally you can pass a message string that will be displayed instead of the default one.
A validator functions takes the current value as input and should return a `boolean` or a `string`. If returned `true` the input counts as valid, if `false` it's not. If you pass a string formhero will treat it as not valid and display the string returned as error message.
2019-09-26 20:53:43 +00:00
###### Example: Regular Expression
```javascript
const validators = {
2019-10-19 06:45:14 +00:00
// Only contains letters.
2019-09-26 20:53:43 +00:00
// This could also be a (also async) function that returns a boolean.
username: /^[A-z]*$/,
}
```
###### Example: Function
```typescript
const validators = {
username: (value: string) => value.lenght > 3,
}
```
###### Example: With Object
```javascript
const validators = {
username: {
validator: /^[A-z]*$/,
message: 'My custom error message',
2019-10-19 06:45:14 +00:00
},
2019-09-26 20:53:43 +00:00
}
```
2019-09-28 17:19:10 +00:00
###### Example: Multiple Validators
```javascript
const validators = {
2019-09-28 17:19:48 +00:00
username: [
{
validator: /^[A-z]*$/,
message: 'My custom error message',
},
/[\d]/,
2019-10-19 06:45:14 +00:00
async value => value.length > 0,
2019-09-28 17:19:48 +00:00
{
2019-10-19 06:45:14 +00:00
validator: value => true,
2019-09-28 17:19:48 +00:00
message: 'Some other error',
2019-10-19 06:45:14 +00:00
},
],
2019-09-28 17:19:10 +00:00
}
```
2019-09-28 17:50:35 +00:00
2019-10-19 18:15:18 +00:00
###### Example: Dynamic Error Message
```javascript
const validators = {
username: async (s: string) => {
const taken = await API.isUsernameTaken(s)
return taken ? 'Username is taken': true
}
}
```
2019-09-28 17:50:35 +00:00
### Options
Sometimes it's practical to have some different default values when using for example react-native or some other framework where the default `value`, `onChange` and `(e)=> e.target.value` do not apply.
###### Example: React Native (Method 1 - Global options)
[Check the Expo Snack for a live preview](https://snack.expo.io/@cupcakearmy/useform)
2019-09-28 17:51:29 +00:00
```javascript
2019-10-19 06:45:14 +00:00
import * as React from 'react'
import { Text, SafeAreaView, TextInput } from 'react-native'
import { useForm } from 'formhero'
2019-09-28 17:50:35 +00:00
const initial = {
username: 'i am all lowercase',
2019-10-19 06:45:14 +00:00
}
const validators = {}
2019-09-28 17:50:35 +00:00
const options = {
setter: 'value', // This is not stricly necessarry as 'value' would already be the default.
getter: 'onChangeText',
extractor: text => text.toLowerCase(),
2019-10-19 06:45:14 +00:00
}
2019-09-28 17:50:35 +00:00
export default () => {
2019-10-19 06:45:14 +00:00
const { form, field } = useForm(initial, validators, options)
2019-09-28 17:50:35 +00:00
return (
<SafeAreaView>
2019-10-19 06:45:14 +00:00
<TextInput style={{ height: 40, borderColor: 'gray', borderWidth: 2 }} {...field('username')} />
2019-09-28 17:50:35 +00:00
<Text>{form.username}</Text>
</SafeAreaView>
2019-10-19 06:45:14 +00:00
)
}
2019-09-28 17:50:35 +00:00
```
###### Example: React Native (Method 2 - Local overwrite)
2019-09-28 17:51:29 +00:00
```javascript
2019-09-28 17:50:35 +00:00
// ...
export default () => {
2019-10-19 06:45:14 +00:00
const { form, field } = useForm({
2019-09-28 17:50:35 +00:00
username: 'i am all lowercase',
2019-10-19 06:45:14 +00:00
})
2019-09-28 17:50:35 +00:00
return (
<SafeAreaView>
<TextInput
style={{ height: 40, borderColor: 'gray', borderWidth: 2 }}
2019-10-19 06:45:14 +00:00
{...field('username', {
2019-09-28 17:50:35 +00:00
setter: 'value', // This is not stricly necessarry as 'value' would already be the default.
getter: 'onChangeText',
extractor: text => text.toLowerCase(),
})}
/>
<Text>{form.username}</Text>
</SafeAreaView>
2019-10-19 06:45:14 +00:00
)
}
2019-09-28 17:50:35 +00:00
```
2019-09-28 18:01:55 +00:00
2019-10-19 06:45:14 +00:00
### field
2019-09-28 18:01:55 +00:00
2019-10-19 06:45:14 +00:00
The `field` object is used to bind the form state to the input.
2019-09-28 18:01:55 +00:00
###### Example: Simple
```javascript
2019-10-19 06:45:14 +00:00
const { field } = useForm()
2019-09-28 18:01:55 +00:00
2019-10-19 06:45:14 +00:00
<input {...field('username')} />
2019-09-28 18:01:55 +00:00
```
###### Example: With custom options
All are optional.
```javascript
2019-10-19 06:45:14 +00:00
const { field } = useForm()
2019-09-28 18:01:55 +00:00
2019-10-19 06:45:14 +00:00
<input {...field('username', {
2019-09-28 18:01:55 +00:00
getter: 'onChage',
setter: 'value',
extractor: (e) => e.target.value
})} />
```
2019-10-19 06:45:14 +00:00
## Form
2019-09-28 18:01:55 +00:00
This is the form state that you can use when submitting the data
2019-10-19 06:45:14 +00:00
###### Example
2019-09-28 18:01:55 +00:00
```javascript
const { form } = useForm(...);
// ...
<form onSubmit={()=> console.log(form)}>
// ...
</form>
```
## Errors
This object contains the error messages if a field is not valid.
The error message can be specified by you, otherwise it will return `Error in ${field}`
###### Example
```javascript
const { errors } = useForm(...)
//...
{errors.username}
{errors.password}
```
2019-09-28 18:02:45 +00:00
## isValid
2019-09-28 18:01:55 +00:00
`isValid` is a little simple helper that checks whether the `error` object is clear or if there are errors left.
2019-10-19 14:56:43 +00:00
## setField
2019-09-28 18:01:55 +00:00
2019-10-19 14:56:43 +00:00
The `setField` function allows you to manually change and assign the state of a field. The type of the field must be the same as the initial type given in the constructor.
2019-09-28 18:01:55 +00:00
###### Example
```javascript
2019-10-19 14:56:43 +00:00
const { form, setField } = useForm(...)
2019-09-28 18:01:55 +00:00
const resetUsername = () => {
2019-10-19 14:56:43 +00:00
setField('username', 'new value')
2019-09-28 18:01:55 +00:00
}
2019-10-19 14:56:43 +00:00
```
## setForm
The `setForm` function allows you to manually change and assign the state of the form. This can be usefull when you want to reset a field or the whole form. The input must have the same type as the initial state.
###### Example
```javascript
const initial = {username: '', password: ''}
const { form, setForm } = useForm(initial, ...)
2019-09-28 18:01:55 +00:00
const resetForm = () => {
2019-10-19 14:56:43 +00:00
setForm(initial)
}
```
## setErrors
The `setErrors` function allows you to manually change and assign the state of the errors. This can be usefull when you want to set an error manually (e.g. sent from the server).
###### Example
```javascript
const { form, setErrors } = useForm(...)
const setError = () => {
setErrors({username: 'Already taken'})
2019-09-28 18:01:55 +00:00
}
```
2019-10-19 09:17:30 +00:00
### Thanks & Attributions
- Thanks for [brendanmckenzie](https://github.com/brendanmckenzie) for suggesting to change `auto` to `field`.