@rpgtec/use-form
v0.1.9
Published
react-hook-form with material-ui
Downloads
6
Maintainers
Readme
@rpgtec/use-storage
Installation
# Using npm
npm i -S @rpgtec/use-form
# Using yarn
yarn add @rpgtec/use-form
Examples
import React from 'react'
import ReactDOM from 'react-dom'
import { useForm, useFieldArray, Form, Field, FieldButton, ErrorMessage } from '@rpgtec/use-form'
// Required only when using type="date"
import LocalizationProvider from '@mui/lab/LocalizationProvider'
import AdapterDateFns from '@mui/lab/AdapterDateFns'
import Box from '@mui/material/Box'
import AddIcon from '@mui/icons-material/Add'
function App() {
const form = useForm({ defaultValues: { name: '', bio: '', birthday: null, lang: 'en', sex: '', job: '', items: [] } })
const items = useFieldArray({ control: form.control, name: 'items' })
const onSubmit = data => {
console.log(data)
return new Promise(resolve => setTimeout(resolve, 1000))
}
const onWrongRequest = data => {
console.log(data)
return new Promise((_, reject) => setTimeout(reject, 1000))
.catch(() => form.setError('_', { message: 'something wrong' }))
}
return (
<Form form={form} onSubmit={onSubmit} spacing>
<Field name="name" label="Name" required />
<Field
name="bio"
label="Biography"
multiline
rows={2}
rules={{ required: true, minLength: 10, maxLength: { value: 100, message: 'too long!' } }}
errorText={{ minLength: 'too short!' }}
/>
<Field name="birthday" label="Birthday" type="date" />
<Field name="lang" label="Lang" options={[{ value: 'en', label: 'English' }, { value: 'ja', label: '日本語' }]} />
<Field name="sex" label="Sex" options={['Male', 'Female', 'Other']} type="radio" row />
<Field name="job" label="Job" options={['Analyst', 'Architect', 'Engineer', 'Manager']} freeSolo />
{items.fields.map((field, index) => (
<Box key={field.id}>
<Field name={`items.${index}.enabled`} type="checkbox" label="Enabled" />
<Field name={`items.${index}.title`} label="Title" />
</Box>
))}
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<FieldButton icon={<AddIcon />} onClick={() => items.append({ enabled: true, title: '' })} />
<Box sx={{ flexGrow: 1 }} />
<ErrorMessage />
<FieldButton onSubmit={onWrongRequest}>Wrong Request</FieldButton>
<FieldButton type="submit">Submit</FieldButton>
</Box>
</Form>
)
}
ReactDOM.render(
<React.StrictMode>
<LocalizationProvider dateAdapter={AdapterDateFns}>
<App />
</LocalizationProvider>
</React.StrictMode>,
document.getElementById('root')
)
Happy hacking!