Skip to main content

Form

Form is a wrapper component for all form elements. You must wrap all of your form elements with the Form component.

Examplesโ€‹

Simple Formโ€‹

import {Form} from 'react-swift-form';

function MyForm() {
return (
<Form initialState={{
// You must specify initial values for all form elements.
}}>
// Form elements and other components goes here
</Form>
);
}

Form with Validationโ€‹

You can use yup to validate form elements.

import {Form} from 'react-swift-form';

function MyForm() {
return (
<Form initialState={{}} validator={{
// You can specify yup schema for each form element.
// Validator must be a plain object, not a yup object schema.
}}>
// Form elements and other components goes here
</Form>
);
}
danger

Validator prop must be a plain object, not a yup object schema.

For example, if you have a string field called name, you can use the following validator:

validator={{ name: yup.string().required() }}

However, you can't use the following yup object schema as a validator:

validator={yup.object({ name: yup.string().required() })}
caution

If you're going to use the validation feature, you must also install yup package separately.

npm install --save yup

Ref handleโ€‹

You can use the ref handle to update form elements without using the Field component's changeValue prop.

import {Form} from 'react-swift-form';
import {useRef} from 'react';

function MyForm() {
const formRef = useRef(null);

const changeSomeValue = () => {
formRef.current?.changeValue('id-of-the-field', 'new value');
}

return (
<div>
<Form ref={formRef}>
// Form elements and other components goes here
</Form>

<button onClick={changeSomeValue}>Change value</button>
</div>
);
}

Propsโ€‹

initialStateโ€‹

Required

The initialState prop is a plain object that contains initial values for all form elements.

It is not recommended to change this prop after the form is rendered.

TypeDefault
Record<string, any>
Required

validatorโ€‹

The validator prop is a plain object that contains validation yup schemas for form elements.

Validator must be a plain object, not a yup object schema.

Validator items can be any yup schema.

TypeDefault
Partial<Record<string, AnySchema>>undefined

Methodsโ€‹

Methods can be accessed by using ref.

changeValueโ€‹

Changes the value of a form element.

Type
(id: string, value: any | ((prevValue: any) => any) => void

changeValuesโ€‹

Changes multiple values at once.

Type
(values: Record<string, any>) => void

changeErrorโ€‹

Changes the error of a form element.

Type
(values: Record<string, string>) => void

changeErrorsโ€‹

Changes multiple errors at once.

Type
(values: Record<string, string>) => void

resetโ€‹

Resets the form to its initial state.

Type
() => void

clearโ€‹

Clears the form.

Type
() => void