Render Props, Apollo and Formik: build and compose forms in React with ease
Originally published on the commercetools tech blog on 29 June 2018. Restored from the Internet Archive.
Please accept my apologies for the clickbaity and buzzword heavy title. I promise the post to be practical from now on. I also hope you enjoy it.
Let’s face it: forms are hard. Especially without a good form library doing the heavy lifting. Forms are easy to get wrong. State management easily becomes error prone. Maintainability of associated code is often brittle. Lastly, forms are often subject to overly eager abstractions in both library- and user land code which leads to a lot of hard to grasp and change “magic” and even worse: performance problems. In this post we will look at:
- How to get API data in and out of forms (from Apollo and GraphQL)
- How to split big forms into smaller building blocks
- How to validate form data during user input and before submission
- How to compose everything using Render Props It is recommended for this post to have a slight understanding of what Apollo and Formik are and solve. No deeper understanding of their internals is necessary.
The task: create and edit a Discount Code
Let us assume we are tasked to build a discount code form. A form to create or edit a discount code which for illustrative purposes only consists of a name and description field. For completeness assume that a user can view discount codes from a list to get to an existing discount code.
The terminology structure of components involved
It is often best to split concerns into meaningful components before starting to write code. Based on our experience so far after trying different approaches, we finally started settling on a structure (or even architecture) we feel comfortable with. From a component-tree perspective, it looks like this. More detailed components implementations will follow.
The <DiscountCodeDetails> receive the needed id from a router while the rest is composed using Render Props. Before we dive into the components in more detail let us discuss their concerns and responsibilities:
- 🦔 **Create or Details: **encapsulates the needed business logic and validation for creating or viewing/editing an existing discount code. It renders the form passing the
initialValues - 🌉 Connector: a component solely responsible for data fetching and offering mutations on it. Passing down so-called fetchers and mutators through its FaaC (Function as a Child)
- 🎹 **Form: **is a collection of fields and encapsulates the validation. It only receives
initialValuesand anonSubmit. It invokesonSubmitwith what we call adraft - 👩👦👦 Subform: a component grouping a set of related fields. It receives mostly only
formikas a prop without abstracting anything additionally (like internal validation or a customonChangecallback) - 🗒 **Field: **a combination of an input and its validation messages. It mostly operates on a single property of the form data (e.g. discount name)
- 🖋 Input: is either of a number input, string input, checkbox or radio. Often for us also quite “complex” input like a custom built
MoneyInputWe established these naming patterns across our teams which helps a lot when looking at a component as it becomes immediately obvious what purpose and reasoning stands behind it.
Having a rough understanding of what components are involved we quickly realized that some utilities are needed to tie things together nicely:
- ⚗️ **Validations: **a small module exporting a
validatefunction. Validation is a form level, not field (or input) level, concern. It will be passed toFormikas a prop. - ⚙️ **Conversions: **a module to cleanly map data into and out of the form so that no field needs to parse or format its data. The module comes with two symmetric functions:
responseToFromValuesandformValuesToRequest. Having component hierarchy and split of concerns figured out we can finally write some code. Up until here, the post was text heavy, now it will focus on code. To ease understanding (hopefully) the order of components will be rearranged starting with the connector and the form.
🌉 Connector: the <DiscountCodeDetailsConnector>
For this post, we will only focus on the <DiscountCodeDetailsConnector> with a <DiscountCodeCreateConnector> being very similar only that passes down a creator and not a fetcher and updater. Please glimpse over the render function:
The <DiscountCodeDetailsConnector> passes down the fetcher and updater for a discount code. Note that the full component’s code is in this gist. The connector in our example uses GraphQL and Apollo but does not have to. One of its goals is to abstract over the data source for the consumers of the connector. Moreover, the example uses the graphql-HoC but does not have to. It could as well use the newer Query and Mutation components. However, the latter is also an implementation detail to the connector. It only standardizes what shape is passed down through children. Here the discountCodeFetcher could, in addition to isLoading and discountCode, also pass down a refetch function.
🎹 Form: the <DiscountCodeForm>
The reasoning behind a form component is to be able to reuse it between the details and a create view. The form itself for this case only renders three fields and does not use subforms as logical grouping as it is not necessary yet:
The Render Prop of the <DiscountCodeForm> passes down control over two form state flags in isDirty and isSubmitting. It also passes down the handleSubmit and handleCancel callbacks. Lastly and interestingly, it also passes down the form React element itself. All of this gives a lot of control to the consumer of the component to compose things together. An example use case would be to disable a header’s deletion button whenever the form is dirty. More on this later (yes I just snuck in this requirement — just like in real life).
🦔 Details: the <DiscountCodeDetails>
Knowing how the <DiscountCodeConnector> and <DiscountCodeForm> works we can easily tie them together in the <DiscountCodeDetails>.
Again, the full implementation of the <DiscountCodeDetails> can be viewed in this gist. Lets see what happens here:
- We render the
<DiscountCodeConnector>to get thediscountCodeFetcherand thediscountCodeUpdater - We render the
<DiscountCodeForm>to compose ourLayoutwhile conditionally disabling an<DeleteIcom>and showing aFormSubmissionStatusMessage - We use our
conversionsmodule andresponseToFormValuesto map the fetched discount code into the form’sinitialValues. In the gist we use the counter part informValuesToRequestto map out of the form on submission and before making a request through thediscountCodeUpdaterThe<DiscountCodeDetails>composes all components nicely. Rendering the<LoadingSpinner>and a<Redirect>becomes very declarative and is easy to test.
🗒 Field(s): the <DiscountCodeNameField>
The last component is the <DiscountCodeNameField> to illustrate how any field could be built.
Here in the<DiscountCodeNameField> we:
- Render a
<TextInput>which is used for any input of this kind and part of our Design System - Wire up the
onChangeandonBlurof the<TextInput>to Formik while passing down anhasErrorandisDisabled(whenever the form is submitting) - Render a
<ValidationError.Switch>and<ValidationError.Match>which is a small React component allowing for more declarative rendering (instead oferror.name && <ErrorMessage />) an<ErrorMessage>
⚗️ Validations: validate
Even if often considered otherwise or even abandoned, validation is one of the most important aspects of forms. It is close to the user and drives and guides engagement with a form. Nothing is more stressful than a form not or falsely submitting without knowing why.
There are different opportunities potentially triggering validation:
- Given input changes: the user is typing
- Given input loses focus: the user leaves a field (e.g. to the next field)
- Given the form submits: user attempts to submit the form
- Given API responds: the server answers
The
validatefunction covers the first three cases while the fact if validation is possible on each change (1.) also depends on the input. Some inputs can only be validated when loosing focus (2.).
There are many approaches as to what is returned by validate. The Formik documentation has more examples and itself even offers a [validationSchema](https://github.com/jaredpalmer/formik#validationschema-schema----schema). Our validations are built to:
- Return an object with boolean flags per field:
{ required: true, duplicate: false } - Not return error messages to be rendered: “Name is required”. Rather to rely on
react-intl‘s<FormattedMessage>in a field Lastly,validateis where a lot of Functional Programming sugar could be added such as a[Validated](https://typelevel.org/cats/datatypes/validated.html)-type. However, this would affect how<ValidationError.Switch>works which is why we settled for boolean flags for now.
⚙️ Conversions: responseToFormValues and formValuesToRequest
The advantages of top level form conversions was a painful lesson for us. Before input level parsing and formatting was the norm. It turns out to be error prone by introducing a lot of accidental complexity. Essentially a form should keep the users original input in state until submitted. Moreover, the form should never have to carry out field/input level parsing.
The example shows how we could deal with parsing and formatting string values or optional fields without the form ever having to be aware of them. Some additional cases
- We should deal with the fact that *nullable GraphQL fields can be *
*null*in responses and set them to be empty strings. Same applies for any other optional property - We should convert empty string values back to
undefinedornullor whatever the API’s contract is - Inputs can export parsing and formatting helpers used here. Our internal
MoneyInputfor instance has a staticMoneyInput.parseMoneyValueandMoneyInput.convertToMoneyValueto be used here Lastly, it should be pointed out that these functions are convenient to test and do not allow leaking any API data into a form.
Conclusions
Maintainable forms depend on good component structure, an awesome form library like Formik and declarative data fetching like Apollo.
Forms do not have to be painful. They can be fun to work on and with. Validation and conversions should be treated as a form level concern, not on each field or input.
By keeping the separation and concerns of components narrow while using Render Props all parts compose naturally. If you want to learn how Render Props can easily be tested head over to our enzyme-extensions. Thanks for reading!