DEV Community

Vu Anh Duc
Vu Anh Duc

Posted on

Stories of Form - First story

Table Of Contents

Most simple form

A form has 1 main feature is collecting data from users. To achieve that, a form should have at least 2 abilities:

  • Displaying input fields
  • Collecting inputted data

The most simple form should be declared like bellow:

import React from "react";
import { Form, Field } from "react-final-form";

export default function SimpleForm() {
  const handleSubmitData = values => {
    console.log("form values", values);
  };
  return (
    <Form onSubmit={handleSubmitData}>
      {formProps => {
        const { handleSubmit } = formProps;
        return (
          <form onSubmit={handleSubmit}>
            <Field name="name" component="input" />
            <button type="submit">Submit</button>
          </form>
        );
      }}
    </Form>
  );
}
  • Input fields are represented by <Field> component
  • When users submit the form, all inputted data are collected and passed to the handleSubmitData function in values parameter

Note

At the first look, final-form syntax seems confused because of Form and form, handleSubmit vs onSubmit... but I think we can survive with it.

Various Field Types

The next request for a Form library is the ability of represents various field types: text field, text area, checkbox, select,...

final-form gives you this power by providing 4 ways to render a field.

Rendering with native component

<Field component="input" name="age" />

Rendering with custom React component


const InputField = ({ input, meta, label }) => {
  return (
    <label for={input.name}>
      {label}
      <input type="text" id={input.name} {...input} />
    </label>
  );
};

<Field name="lastName" component={InputField} label="Last Name" />

Rendering with the render method

<Field
    name="hometown"
    render={({ input, meta }) => {
    return (
        <div>
        <label for="hometown">Home Town</label>
        <input id="hometown" type="text" {...input} />
        </div>
    );
    }}
/>             

Rendering with the children element

<Field name="gender">
    {({ input, meta }) => {
    return (
        <select name={input.name} {...input}>
        <option value="F">Female</option>
        <option value="M">Male</option>
        </select>
    );
    }}
</Field>

Next story: Stories of Form - Validation

Top comments (0)