A small library to build React forms with immutable state, type-safety and not a lot of boilerplate.
npm install formalities
<input>element for checkboxes
<input>element for checkboxes for array properties
<Formalities.Indexed>a component for custom array properties
See the examples for examples of using each of these components.
The case for Formalities
This is how we might manage form state in React components, while maintaining type-safety with TypeScript:
And we could be using Immer so we have immutable state, but that's more boiler-plate.
Using the hook
useController we create a
Controller that reads and updates from the component's state.
In the component we use the Formalities components to create normal
but bound to the value of one of the
Controller's properties, and reporting changes back
to the component state.
Formalities components supports all of the regular
useController returns a
Controller with an initial value. The type of the
determined from that initial value.
<Formalities.Text> component specifies the
Controller instance via the
controller prop, and which property
inside the controller via the
prop prop. Due to the type-safety of the
prop prop can only
accept appropriate value.
Not all components manage their own state. Many components use props to receive state and to report changes.
In this next example the component is a part of a form, reporting changes back to its parent component via
onChange function in its props. The controller uses the
onChange properties from the props
to handle this automatically for you.
In the examples above we've used Formalities's
<Formalities.String> component replacement for the standard
element. You can also create your own components that interact with the controller:
The last line above uses Formalities's to wrap
MyTextField, which accepts props
setValue, to create a component that instead accepts
It can then be used like
<Formalities.Text> in the examples above, as in:
Now when the
MyTextField component wants to change its value, it calls the
setValue function in its
props, which invokes the controller, which updates the state on the
MyForm component, triggering React
to update, which updates the form.
packages/examples directory for more examples.