React, etc. Tech Stack

React, Flux, GraphQL, Hack, HHVM...? All of this and more!

Formstate - Type safe forms for React.js with TypeScript

HTML forms continue to be the bane of existance for developers around the globe. Even with contemporary declarative UI libraries like React, building complex wizards and so on can become a living nightmare.

HTML forms have enabled the transition of the web from a static read only medium, to an interactive one. First the forms were simple, but appetite grew and they forms became increasingly complex.

Numerous server side solutions for form management have been created, and are still in use today. Managing forms on the server is a bit cumbersome, as you're replicating what is in the browser. This is why managing forms in the browser is better.

React.js has become the workhorse for creating applications and forms are increasing in complexities. Simple solutions like JSON Schema form generators are great, but can become cumbersome for edge cases.

Form state management with MobX and TypeScript

Where generic automatic solutions dont work, developers can roll their own state management and form builders. This will easily lead to reinventing the wheel and require maintenance over time.

This is exactly the kind of area where Open Source excels - universal libraries and frameworks to reduce repetition. For forms state management with React.js and TypeScript there is now a project called Formstate, it is a lightweight utility to aid working with tools.

Formstate builds on MobX, a state management well integrated with TypeScript and universally accepted as a good alternative to more complex solutions like Redux that can add unnecessary complexity and boilerplate.

As an added bonus when working with TypeScript you get the usual powerful editing and refactoring capabilities as shown below:

Typeform autocomplete

The FormState project comes from Basarat Ali Syed AKA "That TypeScript Guy" and he lists the following reasoning for creating the project:

The best place to get started is to head to the Formstate documentation, but for a quick start for seasoned React developers code speaks better than words:

/** Standard react - mobx */
import * as React from 'react';
import { observer } from 'mobx-react';

/** Material UI */
import TextField from 'material-ui/TextField';

/** FieldState */
import { FieldState } from '../../index';

 * Field Props
export type FieldProps = {
  /** Any UI stuff you need */
  id: string,
  label: string,

  /** The fieldState */
  fieldState: FieldState<string>

 * Field component. Must be an observer.
export const Field = observer((props: FieldProps) => (
    onChange={function() { props.fieldState.onChange(arguments[1]) }}

Written by Jorgé on Tuesday February 6, 2018

Permalink - Tags: mobx, react, typescript

« Next.js 5 improves TypeScript support - Free eBook on the downfall of Nokia phones: Operation Elop »