fakenickels / fakenickels-blog

fakenickels - Hi, I'm fakenickels
https://blog.fakenickels.dev
5 stars 1 forks source link

Schema based forms with ReForm: type safe form bootstrapping #6

Open fakenickels opened 4 years ago

fakenickels commented 4 years ago

I really miss how easy it was to bootstrap forms in Meteor using autoform together with simple-schema. Even though it was a bit hard to maintain once the form got more complex it was most of the times pretty handy. With the latest release of ReForm we can add a meta info to our form Schema that we could leverage to accomplish something like that with the bonus of having great type safety. So let's create a Tailwind form generator in ReasonML.

What it should look like

We want something that has a usage like

module StateLenses = [%lenses
  type state = {
    name: string,
    age: int,
    acceptedTerms: bool,
  }
];

module SignUpFastForm = FastForm.Make(StateLenses);
[@react.component]
let make = () => {
  let schema =
    SignUpForm.Validation.(
      Schema(
        nonEmpty(
          ~meta=
            FastForm.{
              placeholder: "Maria da Silva",
              label: "Nome",
              kind: Normal,
            },
          Name,
        )
        + int(
            ~min=16,
            ~meta=FastForm.{placeholder: "18", label: "Idade", kind: Normal},
            Age,
          )
        + true_(
            ~meta=
              FastForm.{
                placeholder: "",
                label: "Aceita os termos de uso?",
                kind: Checkbox,
              },
            AcceptedTerms,
          ),
      )
    );

  // Form will be automatically bootstrapped based on the schema of fields passed in
  <div>
    <SignUpFastForm
      initialState=StateLenses.{name: "", age: 0, acceptedTerms: false}
      schema
      onSubmit
    />
  </div>
}