Forms in React.js

Controlled vs. Uncontrolled components:

Controlled components: In controlled components, form data is handled by React state.

Each form input element (e.g., <input>, <textarea>, <select>) receives its current value as a prop and triggers an onChange event handler to update the state.

                                      
                                      import React, { useState } from 'react';

function MyForm() {
  const [value, setValue] = useState('');

  const handleChange = (event) => {
    setValue(event.target.value);
  };

  return (
    <form>
       <input type="text" value={value} onChange={handleChange} />
    </form>
  );
}

                                      
                                    

Uncontrolled components: We lose our control over the data in the uncontrolled mode, since the DOM is in charge of it. The internal states of the input elements are held by them and afterward using a ref on submission you can get their values.

                                      
                                      import React, { useRef } from 'react';

function MyForm() {
  const inputRef = useRef(null);

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log(inputRef.current.value);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" ref={inputRef} />
      <button type="submit">Submit</button>
    </form>
  );
}

                                      
                                    

Form validation:

In this way, validators make sure that user input fulfils certain conditions prior to submission of the form. With this all encompassing check you can even ensure that required fields are filled, email address format is valid, or password is secure enough and so on.

Form validation can be performed by using predefined HTML attributes, custom JavaScript, or form validation libraries.

                                      
                                      import { Formik, Form, Field, ErrorMessage } from 'formik';

function MyForm() {
  return (
    <Formik
      initialValues={{ email: '', password: '' }}
      onSubmit={(values, actions) => {
        console.log(values);
        actions.setSubmitting(false);
      }}
    >
      <Form>
        <Field type="email" name="email" />
        <ErrorMessage name="email" component="div" />
        <Field type="password" name="password" />
        <ErrorMessage name="password" component="div" />
        <button type="submit">Submit</button>
      </Form>
    </Formik>
  );
}

                                      
                                    

React Hook Form: React Hook Form is another popular form library that emphasizes minimalism and performance.

It relies on React hooks for managing form state and validation.

                                      
                                      import { useForm } from 'react-hook-form';

function MyForm() {
  const { register, handleSubmit, errors } = useForm();

  const onSubmit = (data) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input type="text" name="email" ref={register({ required: true })} />
      {errors.email && <span>This field is required</span>}
      <input type="password" name="password" ref={register({ required: true })} />
      {errors.password && <span>This field is required</span>}
      <button type="submit">Submit</button>
    </form>
  );
}