Andrew Egeler
Learning how things work.

React Forms: Using plain HTML forms

TL;DR: I used a plain HTML form instead of a React form builder/manager

At $DAYJOB, I write a bit of React code. For our forms, we currently use formik to manage the form state. The advantage of formik is that it allows us to control state directly with our own code, we can store JS data types directly, and we get good integration with form validation libraries, where validation can run on every keypress.

However, running all form state through a higher-level component and running validation on every keepress can be slow, and can also increase the code complexity. While these issues can be mitigated with the correct settings and effort, in cases where your needs are simpler (such as with a personal project I'm currently working on), a plain HTML form may be all you need. This is especially true with modern browsers, which have useful data types (date, number, etc).

The core difference between the two approaches is that the native-HTML form relies on the browser's input fields to track their own state - this makes things simpler to use and faster to execute, but you give up some flexibility compared to fully managing the state in JS code.

So, without further ado, a simple example showing how straightforward a plain form is with react:

<form
    onSubmit={async (e) => {
      e.preventDefault();
      const form = e.target;
      await doSomething(
        form.textField.value,
        form.dateField.value,
        form.numberField.value
      );
    }}
>
  <div>
    <input name="numberField" type="number" step="0.1" />
  </div>
  <div>
    <input name="dateField" type="date" />
  </div>
  <div>
    <input name="textField" type="text" required />
  </div>
</form>