Mutating data

Forms in React

Creating a form in react requires some programming. You need to create the form fields, keep the state synchronized with changes to the field, and validate the form input(s) on submit. The w3schools react forms tutorial has a great set of examples that shows how this could be implemented. Spoiler: It's a lot of code.

When building DHIS2 applications we don't have to do all of that. Similar to how the DHIS2 core team makes it easier to query the API with react-query, they make it simpler to create forms in React by implementing React Final Form.

React Final Form in DHIS2

React Final form simplifies creating forms because all of the form inputs state is abstracted away. The DHIS2 core team has also created a set of form validators. Instead of writing checks in Javascript trying to figure out if an input is empty, a number, or a minimum length you can simply import these checks from the DHIS2 UI component library. These validators also serve useful error messages to the end-user, improving the data-entry experience.

Using Final Form in DHIS2 applications

A code example is worth a thousand words.

- Ghandi

import { ReactFinalForm, InputFieldFF, Button, hasValue } from '@dhis2/ui'
function onSubmit(values) {
alert(JSON.stringify(values))
}
function Form(props) {
return (
<ReactFinalForm.Form onSubmit={onSubmit}>
{({ handleSubmit }) => (
<form onSubmit={handleSubmit}>
<ReactFinalForm.Field
name="Population"
label="Population"
component={InputFieldFF}
validate={hasValue}
/>
<Button type="submit" primary>
Submit
</Button>
</form>
)}
</ReactFinalForm.Form>
)
}

Explanation

  • First we import FinalForm, our DHIS2 UI components, and our hasValue validator. Note that we import InputFieldFF. All DHIS2 UI components ending with FF can be used with Final Form.
  • The we create a function that alerts() the field input when the form is submitted.
  • Finally we create a FinalForm.Form that's wrapped around an html form that contains a Field. The field recieves the DHIS2 UI component InputFieldFF and the validator hasValue as props.

This may seem a bit convoluted at first glance, but it is surprisingly intuitive to get started with. If you copy the code example above you can easily modify the form and add more fields. If you want to learn more about FinalForm start here:

In the next section we will create the form that we will be using in our application.