Getting Started
Lets install both react-formal
and yup
.
npm install react-formal yup
For older browsers without the
Promise
as well asSet
andMap
global object, you'll need to include a polyfill such ases6-promise
, orcore-js
.
Creating a Form
React Formal consolidates and tracks form state. Input values are mapped
to an overall form value via their name
. It works very similar to how you might serialize
a native HTML form.
Forms are made up of <Field>
s, and you can use almost any component as
a field. The only expectation React Formal has it that the field component accept a value
and report changes by calling an injected onChange
callback. It's the same
contract as plain controlled inputs in React.
The example below is a single form Field
made up of an input and button.
Passing React Formal onChange
handlers to native inputs will Just Work. The target
value
is pulled from the event correctly and passed up. However, you do not need to pass
an event, and can instead pass the input value
by itself.
Adding Validation
Most forms need some sort of value validation. Sometimes is simple, but often it
can get very complex. In order to handle all the cases React Formal relies on yup
,
a small, schema-based. validation library. For more infomation about how schema
affect forms see: Form Schema.
A schema, tells each form how and where to validate it's inputs, hit submit to see the issue here:
You can easily control how and and when fields trigger validation as well. Consult
the FormSubmit
and Field
API docs for more infomation.
Submitting a form
Once a form is complete it's time to submit it, collect the form data and maybe
save it to a server. You've already seen the <Form.Submit>
component above, which
triggers a form wide validation.
When you click Submit
the form enters a "submitting" phase while it runs validation
again. If validation succeeds an onSubmit
callback will fire. After which React Formal
considers the submission finished and is ready to continue processing input.
React Formal gives you additional hooks to control how submission works. For instance
you may want your Submit buttons to provide feadback while saving data to the server.
submitForm
allows you do do async work while the Form waits for you to finish.
In this example we change the button text to "submitting…" while saving
the form data to a server.
And that's the basics of how React Formal works. Consult the API documentation for more tips and tricks.