rename auto to field

This commit is contained in:
cupcakearmy 2019-10-19 08:45:14 +02:00
parent 0cf1b6e73b
commit 5d6a420283
8 changed files with 249 additions and 256 deletions

122
README.md
View File

@ -22,9 +22,9 @@ npm i formhero
### 👁 Demos ### 👁 Demos
- [__*Live Web*__](https://cupcakearmy.github.io/formhero/) - [**_Live Web_**](https://cupcakearmy.github.io/formhero/)
- [__*Live Codesandbox*__](https://codesandbox.io/embed/formhero-simple-bdcx2?expanddevtools=1&fontsize=14) - [**_Live Codesandbox_**](https://codesandbox.io/embed/formhero-simple-bdcx2?expanddevtools=1&fontsize=14)
- [__*Live React-Native*__](https://snack.expo.io/@cupcakearmy/useform) - [**_Live React-Native_**](https://snack.expo.io/@cupcakearmy/useform)
### Links ### Links
@ -35,7 +35,7 @@ npm i formhero
- [Validators](#validators) - [Validators](#validators)
- [Options](#options) - [Options](#options)
- Returns - Returns
- [auto](#auto) - [field](#field)
- [form](#form) - [form](#form)
- [errors](#errors) - [errors](#errors)
- [isValid](#isvalid) - [isValid](#isvalid)
@ -54,8 +54,7 @@ import ReactDOM from 'react-dom'
import { useForm } from 'formhero' import { useForm } from 'formhero'
const Form = () => { const Form = () => {
const { field, form } = useForm({
const { auto, form } = useForm({
username: '', username: '',
password: '', password: '',
}) })
@ -68,9 +67,8 @@ const Form = () => {
return ( return (
<div> <div>
<form onSubmit={_submit}> <form onSubmit={_submit}>
<input {...field('username')} />
<input {...auto('username')} /> <input {...field('password')} />
<input {...auto('password')} />
<button type="submit">Go 🚀</button> <button type="submit">Go 🚀</button>
</form> </form>
@ -85,12 +83,13 @@ const Form = () => {
```typescript ```typescript
const Form = () => { const Form = () => {
const { field, form, errors } = useForm(
const { auto, form, errors } = useForm({ {
username: '', username: '',
email: '', email: '',
password: '' password: '',
}, { },
{
username: value => value.length > 3, username: value => value.length > 3,
email: { email: {
validator: /@/, validator: /@/,
@ -99,29 +98,28 @@ const Form = () => {
password: [ password: [
{ {
validator: /[A-Z]/, validator: /[A-Z]/,
message: 'Must contain an uppercase letter' message: 'Must contain an uppercase letter',
}, },
{ {
validator: /[\d]/, validator: /[\d]/,
message: 'Must contain a digit' message: 'Must contain a digit',
}, },
] ],
}) }
)
return ( return (
<form> <form>
<h1>Errors & Validation</h1> <h1>Errors & Validation</h1>
<input {...auto('username')} placeholder="Username" /> <input {...field('username')} placeholder="Username" />
{errors.username && 'Must be longer than 3'} {errors.username && 'Must be longer than 3'}
<input {...auto('email')} placeholder="EMail" /> <input {...field('email')} placeholder="EMail" />
{errors.email} {errors.email}
<input {...auto('password')} placeholder="Password" type="password" /> <input {...field('password')} placeholder="Password" type="password" />
{errors.password} {errors.password}
</form> </form>
) )
} }
@ -133,30 +131,32 @@ Often it happens that you use a specific input or framework, so the default gett
```typescript ```typescript
const Form = () => { const Form = () => {
const { field, form, errors } = useForm({
const { auto, form, errors } = useForm({
awesome: true, awesome: true,
}) })
return ( return (
<form onSubmit={e => { <form
onSubmit={e => {
e.preventDefault() e.preventDefault()
console.log(form) console.log(form)
}}> }}
>
<h1>Custom</h1> <h1>Custom</h1>
<label> <label>
<input type="checkbox" {...auto('awesome', { <input
type="checkbox"
{...field('awesome', {
setter: 'checked', setter: 'checked',
getter: 'onChange', getter: 'onChange',
extractor: (e) => e.target.checked extractor: e => e.target.checked,
})} /> })}
/>
Is it awesome? Is it awesome?
</label> </label>
<input type="submit" /> <input type="submit" />
</form> </form>
) )
} }
@ -167,7 +167,7 @@ const Form = () => {
### `useForm` ### `useForm`
```typescript ```typescript
const {auto, errors, update, form, isValid} = useForm(initial, validators, options) const { field, errors, update, form, isValid } = useForm(initial, validators, options)
``` ```
### Initial ### Initial
@ -213,7 +213,7 @@ const validators = {
username: { username: {
validator: /^[A-z]*$/, validator: /^[A-z]*$/,
message: 'My custom error message', message: 'My custom error message',
} },
} }
``` ```
@ -227,12 +227,12 @@ const validators = {
message: 'My custom error message', message: 'My custom error message',
}, },
/[\d]/, /[\d]/,
async (value) => value.length > 0, async value => value.length > 0,
{ {
validator: (value) => true, validator: value => true,
message: 'Some other error', message: 'Some other error',
} },
] ],
} }
``` ```
@ -245,33 +245,30 @@ Sometimes it's practical to have some different default values when using for ex
[Check the Expo Snack for a live preview](https://snack.expo.io/@cupcakearmy/useform) [Check the Expo Snack for a live preview](https://snack.expo.io/@cupcakearmy/useform)
```javascript ```javascript
import * as React from 'react'; import * as React from 'react'
import { Text, SafeAreaView, TextInput } from 'react-native'; import { Text, SafeAreaView, TextInput } from 'react-native'
import { useForm } from 'formhero'; import { useForm } from 'formhero'
const initial = { const initial = {
username: 'i am all lowercase', username: 'i am all lowercase',
}; }
const validators = {}; const validators = {}
const options = { const options = {
setter: 'value', // This is not stricly necessarry as 'value' would already be the default. setter: 'value', // This is not stricly necessarry as 'value' would already be the default.
getter: 'onChangeText', getter: 'onChangeText',
extractor: text => text.toLowerCase(), extractor: text => text.toLowerCase(),
}; }
export default () => { export default () => {
const { form, auto } = useForm(initial, validators, options); const { form, field } = useForm(initial, validators, options)
return ( return (
<SafeAreaView> <SafeAreaView>
<TextInput <TextInput style={{ height: 40, borderColor: 'gray', borderWidth: 2 }} {...field('username')} />
style={{ height: 40, borderColor: 'gray', borderWidth: 2 }}
{...auto('username')}
/>
<Text>{form.username}</Text> <Text>{form.username}</Text>
</SafeAreaView> </SafeAreaView>
); )
}; }
``` ```
###### Example: React Native (Method 2 - Local overwrite) ###### Example: React Native (Method 2 - Local overwrite)
@ -280,15 +277,15 @@ export default () => {
// ... // ...
export default () => { export default () => {
const { form, auto } = useForm({ const { form, field } = useForm({
username: 'i am all lowercase', username: 'i am all lowercase',
}); })
return ( return (
<SafeAreaView> <SafeAreaView>
<TextInput <TextInput
style={{ height: 40, borderColor: 'gray', borderWidth: 2 }} style={{ height: 40, borderColor: 'gray', borderWidth: 2 }}
{...auto('username', { {...field('username', {
setter: 'value', // This is not stricly necessarry as 'value' would already be the default. setter: 'value', // This is not stricly necessarry as 'value' would already be the default.
getter: 'onChangeText', getter: 'onChangeText',
extractor: text => text.toLowerCase(), extractor: text => text.toLowerCase(),
@ -296,33 +293,30 @@ export default () => {
/> />
<Text>{form.username}</Text> <Text>{form.username}</Text>
</SafeAreaView> </SafeAreaView>
); )
}; }
``` ```
### Auto ### field
The `auto` object is used to bind the form state to the input.
The `field` object is used to bind the form state to the input.
###### Example: Simple ###### Example: Simple
```javascript ```javascript
const { auto } = useForm() const { field } = useForm()
<input {...auto('username')} /> <input {...field('username')} />
``` ```
###### Example: With custom options ###### Example: With custom options
All are optional. All are optional.
```javascript ```javascript
const { auto } = useForm() const { field } = useForm()
<input {...auto('username', { <input {...field('username', {
getter: 'onChage', getter: 'onChage',
setter: 'value', setter: 'value',
extractor: (e) => e.target.value extractor: (e) => e.target.value

View File

@ -4,30 +4,32 @@ import ReactDOM from 'react-dom'
import { useForm } from '../dist' import { useForm } from '../dist'
const Index: React.FC = () => { const Index: React.FC = () => {
const { field, form, errors } = useForm({
const { auto, form, errors } = useForm({
awesome: true, awesome: true,
}) })
return ( return (
<form onSubmit={e => { <form
onSubmit={e => {
e.preventDefault() e.preventDefault()
console.log(form) console.log(form)
}}> }}
>
<h1>Custom</h1> <h1>Custom</h1>
<label> <label>
<input type="checkbox" {...auto('awesome', { <input
type="checkbox"
{...field('awesome', {
setter: 'checked', setter: 'checked',
getter: 'onChange', getter: 'onChange',
extractor: (e) => e.target.checked extractor: e => e.target.checked,
})} /> })}
/>
Is it awesome? Is it awesome?
</label> </label>
<input type="submit" /> <input type="submit" />
</form> </form>
) )
} }

View File

@ -4,12 +4,13 @@ import ReactDOM from 'react-dom'
import { useForm } from '../' import { useForm } from '../'
const Index: React.FC = () => { const Index: React.FC = () => {
const { field, form, errors, isValid } = useForm(
const { auto, form, errors, isValid } = useForm({ {
username: '', username: '',
email: '', email: '',
password: '' password: '',
}, { },
{
username: value => value.length > 3, username: value => value.length > 3,
email: { email: {
validator: /@/, validator: /@/,
@ -18,34 +19,35 @@ const Index: React.FC = () => {
password: [ password: [
{ {
validator: /[A-Z]/, validator: /[A-Z]/,
message: 'Must contain an uppercase letter' message: 'Must contain an uppercase letter',
}, },
{ {
validator: /[\d]/, validator: /[\d]/,
message: 'Must contain a digit' message: 'Must contain a digit',
}, },
] ],
}) }
)
return ( return (
<form onSubmit={(e) => { <form
onSubmit={e => {
e.preventDefault() e.preventDefault()
if (isValid) console.log(form) if (isValid) console.log(form)
}}> }}
>
<h1>Errors & Validation</h1> <h1>Errors & Validation</h1>
<input {...auto('username')} placeholder="Username" /> <input {...field('username')} placeholder="Username" />
{errors.username && 'Must be longer than 3'} {errors.username && 'Must be longer than 3'}
<input {...auto('email')} placeholder="EMail" /> <input {...field('email')} placeholder="EMail" />
{errors.email} {errors.email}
<input {...auto('password')} placeholder="Password" type="password" /> <input {...field('password')} placeholder="Password" type="password" />
{errors.password} {errors.password}
<input type="submit" /> <input type="submit" />
</form> </form>
) )
} }

View File

@ -1,8 +1,7 @@
<html lang="en"> <html lang="en">
<head>
<head> <meta charset="UTF-8" />
<meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Hero</title> <title>Form Hero</title>
<style> <style>
body { body {
@ -17,39 +16,38 @@
margin: 1em auto; margin: 1em auto;
padding: 1em; padding: 1em;
background-color: #f3f3f3; background-color: #f3f3f3;
border-radius: .5em; border-radius: 0.5em;
box-shadow: 0 8px 16px -16px rgba(0, 0, 0, .5); box-shadow: 0 8px 16px -16px rgba(0, 0, 0, 0.5);
} }
input { input {
font-size: 1.25em; font-size: 1.25em;
display: block; display: block;
padding: .5em 1em; padding: 0.5em 1em;
margin-top: .5em; margin-top: 0.5em;
border-radius: 1em; border-radius: 1em;
width: 100%; width: 100%;
outline: none; outline: none;
border: .15em solid white; border: 0.15em solid white;
} }
input:focus, input:focus,
input:hover { input:hover {
border-color: #31def5; border-color: #31def5;
} }
input[type="submit"] { input[type='submit'] {
cursor: pointer; cursor: pointer;
} }
input[type="checkbox"] { input[type='checkbox'] {
display: inline; display: inline;
width: initial; width: initial;
} }
</style> </style>
</head> </head>
<body> <body>
<section> <section>
<h3>Open the console to see the submitted data</h3> <h3>Open the console to see the submitted data</h3>
</section> </section>
@ -62,6 +60,5 @@
<script src="./errorsAndValidation.tsx"></script> <script src="./errorsAndValidation.tsx"></script>
<script src="./select.tsx"></script> <script src="./select.tsx"></script>
<script src="./custom.tsx"></script> <script src="./custom.tsx"></script>
</body> </body>
</html> </html>

View File

@ -4,20 +4,20 @@ import ReactDOM from 'react-dom'
import { useForm } from '../dist' import { useForm } from '../dist'
const Index: React.FC = () => { const Index: React.FC = () => {
const { field, form, errors } = useForm({
const { auto, form, errors } = useForm({
type: 'formhero', type: 'formhero',
}) })
return ( return (
<form onSubmit={e => { <form
onSubmit={e => {
e.preventDefault() e.preventDefault()
console.log(form) console.log(form)
}}> }}
>
<h1>Select</h1> <h1>Select</h1>
<select {...auto('type')}> <select {...field('type')}>
<option value="redux-form">Redux-Form</option> <option value="redux-form">Redux-Form</option>
<option value="react-hook-forms">React-Hook-Forms</option> <option value="react-hook-forms">React-Hook-Forms</option>
<option value="formik">Formik</option> <option value="formik">Formik</option>
@ -25,7 +25,6 @@ const Index: React.FC = () => {
</select> </select>
<input type="submit" /> <input type="submit" />
</form> </form>
) )
} }

View File

@ -4,25 +4,24 @@ import ReactDOM from 'react-dom'
import { useForm } from '../dist' import { useForm } from '../dist'
const Index: React.FC = () => { const Index: React.FC = () => {
const { field, form, errors } = useForm({
const { auto, form, errors } = useForm({
username: 'unicorn', username: 'unicorn',
password: '', password: '',
}) })
return ( return (
<form onSubmit={e => { <form
onSubmit={e => {
e.preventDefault() e.preventDefault()
console.log(form) console.log(form)
}}> }}
>
<h1>Simple</h1> <h1>Simple</h1>
<input {...auto('username')} placeholder="Username" /> <input {...field('username')} placeholder="Username" />
<input {...auto('password')} placeholder="Password" type="password" /> <input {...field('password')} placeholder="Password" type="password" />
<input type="submit" /> <input type="submit" />
</form> </form>
) )
} }

View File

@ -88,10 +88,10 @@ export const useForm = <T, U extends { [key in keyof T]: useFormValidatorParamet
_validate(key, extracted) _validate(key, extracted)
} }
const auto = (key: keyof T, opts: useFormOptions = {}) => ({ const field = (key: keyof T, opts: useFormOptions = {}) => ({
[opts.getter || options.getter || 'onChange']: update(key, opts.extractor), [opts.getter || options.getter || 'onChange']: update(key, opts.extractor),
[opts.setter || options.setter || 'value']: form[key] as any, [opts.setter || options.setter || 'value']: form[key] as any,
}) })
return { form, update, auto, errors, isValid } return { form, update, field, errors, isValid }
} }

View File

@ -6,7 +6,7 @@ import { useForm } from '../'
const TextError: React.FC<{ error?: string }> = ({ error }) => (!error ? null : <div className="has-text-danger">{error}</div>) const TextError: React.FC<{ error?: string }> = ({ error }) => (!error ? null : <div className="has-text-danger">{error}</div>)
const Index: React.FC = () => { const Index: React.FC = () => {
const { auto, form, errors, isValid } = useForm( const { field, form, errors, isValid } = useForm(
{ {
username: '', username: '',
password: '', password: '',
@ -40,20 +40,20 @@ const Index: React.FC = () => {
<div> <div>
<form onSubmit={_submit}> <form onSubmit={_submit}>
<div>Username</div> <div>Username</div>
<input className="input" {...auto('username')} /> <input className="input" {...field('username')} />
<TextError error={errors.username} /> <TextError error={errors.username} />
<br /> <br />
<br /> <br />
<div>Password</div> <div>Password</div>
<input className="input" {...auto('password')} /> <input className="input" {...field('password')} />
<TextError error={errors.password} /> <TextError error={errors.password} />
<br /> <br />
<br /> <br />
<div>Which one to choose?</div> <div>Which one to choose?</div>
<div className="select"> <div className="select">
<select {...auto('type')}> <select {...field('type')}>
<option value="redux-form">Redux-Form</option> <option value="redux-form">Redux-Form</option>
<option value="react-hook-forms">React-Hook-Forms</option> <option value="react-hook-forms">React-Hook-Forms</option>
<option value="formik">Formik</option> <option value="formik">Formik</option>
@ -66,7 +66,7 @@ const Index: React.FC = () => {
<label className="checkbox"> <label className="checkbox">
<input <input
type="checkbox" type="checkbox"
{...auto('awesome', { {...field('awesome', {
setter: 'checked', setter: 'checked',
getter: 'onChange', getter: 'onChange',
extractor: e => e.target.checked, extractor: e => e.target.checked,