Free React Course
For Beginners

L7 - Forms - Default way and React-Hook-Forms

React For Beginners by Itera

Key Points

  • React Forms - default way
  • Building your first form with React Hook Form
  • Validation with Yup

React Forms - default way

Controlled Forms

The kind of a form where values for the fields controlled by the state

Create a component with empty form and state

class MyForm extends PureComponent {
    state = { pwd: "" };
    render() {
        return (
            

My form

); } }

Add an input inside the form

<input
    type="password"
    name="pwd"
    id="pwd"
    value={this.state.pwd}
    onChange={this._handleChange}
/>

Add handler for the input which will update the state

private _handleChange = (e: ChangeEvent<HTMLInputElement>) =>
    this.setState({ pwd: e.target.value });

Add handler to show formData on submit

private _handleSubmit = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    console.log(`Form state`, this.state);
};

Work is done, full example here

Apart from controlled forms, there are uncontrolled forms

However, they are way less used

This approach doesn't scale well and might become very repetitive

Building your first form with React-Form-Hook

React-Form-Hook@7.29.0

  • ⭐ 27_000
  • Downloads: 1,663,244
  • Size: 24kB

Install react-hook-form

npm i react-hook-form

Convert class to function

const MyForm: FC = () => {
    return (
        <form>
            <h1>My form</h1>
            <input type="password" />
            

<button>Submit</button>

</form> ); };

Use useForm from the package

const { register, handleSubmit } = useForm<{ pwd: string }>();

Register field in the form

<input type="password" {...register("pwd")} />

Result

const MyForm = () => {
    const { register, handleSubmit } = useForm<FormData>();
    const submit = (d) => console.log(d);
    return (
        <form onSubmit={handleSubmit(submit)} name="myform">
            <h1>My form</h1>
            <input type="password" {...register("pwd")} />
            <p> <button>Submit</button> </p>
        </form>
    );
};

This doesn't seem much better, yeah?

Validations

React-Form-Hooks make validation easy and customizable

Define validation rules

const pwd = { 
    required: { value: true, message: "password required" } 
    minLength: { value: 6, message: "Too short!" }
};        

Pass validations into the registrants

<input type="text" {...register("pwd", pwd)} />

Show an error if something went wrong

<div>{formState.errors?.pwd?.message}</div>

React-form-hook is very configurable

  • Supports custom validation with validate method
  • Supports async validation
  • Support nested data objects

Warning

React-Form-Hook works only with Functional Components

Consider using React.memo when performance is crucial

Validation with Yup

To make validations even easier, you can use Yup

Yup - platform agnostic javascript library for the declarative validation

Yup - 0.32.11

  • 16_700 ⭐
  • 2,861,507 downloads
  • 60kB size

Define validation schema

import { BaseSchema, InferType, object, string } from "yup";
const validationSchema = object({
    email: string().required().email(),
    password: string().required().min(6).max(12),
});

Connect schema to the form using some hook magic

const validations = useYup(validationSchema);
const { register, handleSubmit, formState } = 
    useForm<FormData>({resolver: validations});

You a good to go

The main advantage - validation logic moved out of the form and can be reused

Disadvantages

  • Learning curve with TS
  • Size - 60kB for validation is pretty much, however version 1 should be around 40kB

When to use

  • For a complex models
  • When need to share the validation logic

Useful links

Join me

Twitter
GitHub