DEV Community

Vu Anh Duc
Vu Anh Duc

Posted on

1

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

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post →

Top comments (0)

Sentry mobile image

Improving mobile performance, from slow screens to app start time

Based on our experience working with thousands of mobile developer teams, we developed a mobile monitoring maturity curve.

Read more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay