@oladimillion/react-form v1.0.5
react-form
Fast and easy way to create form in React
Installation
Using npm
npm install @oladimillion/react-formUsing yarn
yarn add @oladimillion/react-formBasic Usage
import { Form, Field, SubmitButton } from '@oladimillion/react-form'
const validationRules = {
text: {
validation: ['required'],
message: {
required: 'This text field is required'
}
},
}
const initialValues = {
text: 'react form',
}
const MyForm = () => {
const onSubmit = async ({ values, errors, submitting, resetForm, setFormError, setFormValue }) => {
// perform async action here
}
return (
<Form
onSubmit={onSubmit}
validationRules={validationRules}
initialValues={initialValues}
>
<Field type='text' label='Text Field' name='text' placeholder='Text field' />
...
<SubmitButton>Save</SubmitButton>
</Form>
)
}API
<Form />
Form handles the form's validation, change and submit events.
<Form
onSubmit={onSubmit}
validationRules={validationRules}
initialValues={initialValues}
readOnly={false}
>
...
</Form>Form props
onSubmit(Object: { values: object, errors: objects, submitting: boolean, resetForm: function, setFormError: function, setFormValue: function })requiredCalled when submit event is triggered.
values: objectKey-value pair of field names and values.
errors: objectKey-value pair of field names and errors.
submitting: booleantruewhen form is submitting.setFormValue(values: object, useInitialValues: boolean): voidUpdates the form state with
values.setFormError(errors: object, useInitialErrors: boolean): voidUpdates the form state with
errors.resetForm(): voidResets the form state.
validationRules: objectAllows form fields custom validation.
Validatorjs is used in the form validation.
const validationRules = { email: { validation: 'required|email', // validation in string format } } const validationRules = { email: { validation: ['required', 'email'], // validation in array format } } // custom validation message const validationRules = { email: { validation: ['required', 'email'], message: { required: 'Email field is required', email: 'Email provided is invalid', } } } /* `depend` manages the dependency of a field on other fields */ // depend as a function const validationRules = { email: { ... depend: (values, fieldName, fieldIndex) => { // `values` is the fields value in the form state // `fieldName` is the field name the depend is running against. // `fieldIndex` is the index of field in a field array. null for a non-array field. // perform your check here // return a boolean value (true or false) } } } // depend as an object const validationRules = { email: { ... depend: { field1: 'value1', field2: 'value2' } // email is dependent on field1 and field2 } } // depend as a string const validationRules = { email: { ... depend: 'field1' // email is dependent on field1 } } // depend as a boolean const validationRules = { email: { ... depend: true // `false` will hide email field } }Validation rule for a
FieldArrayusing dot notationconst validationRules = { fieldArray.*.email: { validation: ['required', 'email'], } }initialValues: objectDefining initial value for form fields
readOnly: booleanFormcan be made read only by settingreadOnlyprop totrue
<Field />
Field hooks up inputs to the form state using the name attribute.
import { Field } from '@oladimillion/react-form'
...
<Field type='password' label='Password' name='password' />
...Field props
name: stringrequiredFieldname in the form state.type: stringInput types, which can be
text,textarea,select,checkbox,radio,switch,email,url,password,file, ornumber.
placeholder: stringPlaceholder text for
text,textarea,email,url,select,passwordandnumberinput types.label: stringFieldlabel.renderLabel: functionlabelcan be customized using therenderLabelprop.<Field renderLabel={() => <label>My label</label>} ... />renderErrorMessage(Object: { errors: array }): ReactComponent<array>Field's error messages can be customized using the
renderErrorMessageprop.<Field renderErrorMessage={({ errors }) => errors.map(error => <span>{error}</span>)} ... />options: arrayradioandselectinput types recievesoptionsprop to render choices.optionsis a list oftext: stringandvalue: number|boolean|stringobject.// radio input type <Field label='Radio Field' options={[{ text: 'Yes', value: 'yes' }, {text: 'No', value: 'no' }]} type='radio' name='radio' />// select input type <Field label='Select Field' options={[{ text: 'Good', value: 3 }, { text: 'Better', value: 2 }, { text: 'Best', value: 1 }]} type='select' name='select2' placeholder='Placeholder Text' />as: ReactComponentInput fields are rendered using Semantic UI React components. But with
asprop, custom input field can be rendered instead.const TextArea = (props) => <textarea {...props} row={3} placeholder='description...' /> <Field label='Text area' name='textarea' as={TextArea} />
<FieldArray />
Groups of Field can be rendered using FieldArray.
Each Field in a FieldArray must have a name composed from the FieldArray name, field index and field name. eg. group.1.email
import { Field, FieldArray } from '@oladimillion/react-form'
...
<FieldArray name='fieldArray' label='Field Array'>
{({ values, add, remove }) => (
<FieldArray.Item mb={2}>
{values.map((_, index) => (
<FieldArray.Item key={index}>
<FieldArray.RemoveButton onClick={() => remove(index)} />
<Field type='textarea' label='TextArea Field' name={`fieldArray.${index}.textarea`} />
<FieldArray.Divider />
</FieldArray.Item>
))}
<FieldArray.AddButton onClick={add} />
</FieldArray.Item>
)}
</FieldArray>
...FieldArray props
name: stringrequiredFieldArrayname in the form state.label: stringFieldArraylabel.render(object: { value: array, add: function, remove: function }): ReactComponentvaluesholds the items' value,add(value: any): voidadds a new item to the array fields, andremove(index: integer): voidremoves an item from the array fields using its index.
<FieldArray
...
render={({ values, add, remove }) => (...)}
/>children(object: { value: array, add: function, remove: function }): ReactComponentSame as
renderprop, but the function is passed as children.
<FieldArray
...
>
{({ values, add, remove }) => (...)}
</FieldArray>useField
useField is a custom react hook that let you hook up to the form state using the field name.
import { useField, Form } from '@oladimillion/react-form'
const CustomField = () => {
const name = 'text'
const { value, onChange, onBlur, required, readOnly } = useField(name)
return (
<div>
<label>Field label</label>
<input
value={value}
onChange={onChange}
onBlur={onBlur}
required={required}
disabled={readOnly}
name={name}
type='text'
/>
</div>
)
}
const MyForm = () => {
const onSubmit = () => {}
return (
<Form onSubmit={onSubmit}>
<CustomField />
...
</Form>
)
}useField returned props
value: anyField's value.
error: arrayField's validation error.
onChange(e: ChangeEvent): voidChange event handler.
handleChange(e: ChangeEvent): voidChange event handler.
onBlur(e: BlurEvent): voidBlur event handler.
setValue(value: any): voidSet the field's value.
setError(error: string): voidSet the field's error.
useFormContext
useFormContext is a custom react hook that let you hook up to the form state.
import { useFormContext } from '@oladimillion/react-form'
const formContext = useFormContext()useFormContext returned props
values: objectForm fields' value.
errors: objectForm fields' validation error.
handleSubmit(e: SubmitEvent): voidSubmit event handler.
handleChange(e: ChangeEvent): voidChange event handler.
onBlur(e: BlurEvent): voidBlur event handler.
setFieldValue(fieldName: string, fieldValue: any): voidSet the field's value.
setFieldError(fieldName: string, fieldError: string): voidSet the field's error.
setSubmitting(submitting: boolean): voidSet
submittingtotrueorfalse.resetForm(): voidResets the form state.
submitting: booleantruewhen form is submitting.dirty: booleantruewhen form is dirty.readOnly: booleantruewhen form is read only.setFormValue(values: object, useInitialValues: boolean): voidUpdates the form state with
values.setFormError(errors: object, useInitialErrors: boolean): voidUpdates the form state with
errors.
License
This project is licensed under the terms of the MIT license.