React Forms Tutorial

In this tutorial, you will learn what are the forms and how to render them in React.

What are React Forms?

  1. React forms are essential for gathering and processing user input.
  2. In React, forms are created using HTML form elements and managed using state.
  3. To create a React form, you need to use the <form> element. You can then add input fields, text areas, and other form elements to the form.
const Form = () => {
    const [name, setName] = useState('');
    const [email, setEmail] = useState('');
  
    const handleSubmit = (event) => {
      event.preventDefault();
  
      // Submit the form data to a server
    };
  
    return (
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          name="name"
          placeholder="Your name"
          value={name}
          onChange={(event) => setName(event.target.value)}
        />
        <input
          type="email"
          name="email"
          placeholder="Your email"
          value={email}
          onChange={(event) => setEmail(event.target.value)}
        />
        <button type="submit">Submit </button>
    </form>
    );
  };
  

Controlled vs. Uncontrolled Components in React

  1. In React, forms can be controlled or uncontrolled.
  2. Controlled components are React components where the form data is controlled by React state.
  3. Uncontrolled components rely on the DOM to store and manage form data.
<input
    type="text"
    value={this.state.inputValue}
    onChange={this.handleChange}
/>
  

Handling Form Submissions

  1. To handle form submissions, you can use the onSubmit event handler on the <form> element.
  2. Use e.preventDefault() to prevent the default form submission behavior.
handleSubmit = (e) => {
    e.preventDefault();
    // Process form data and submit
  }
  

Conditional Rendering

  1. Conditional rendering allows you to show/hide form elements based on user interactions or state.
  2. Use the render() method to conditionally display form elements.
{this.state.showAdditionalField && (
    <input
      type="text"
      value={this.state.additionalValue}
      onChange={this.handleAdditionalChange}
    />
  )}
  

Form Libraries

  1. For complex forms, consider using form libraries like Formik or React Hook Form.
  2. These libraries simplify form handling and validation.
import { Formik, Form, Field, ErrorMessage } from 'formik';

<Formik
    initialValues={{ name: '', email: '' }}
    onSubmit={values => {
    // Handle form submission
    }}
>
    <Form>
        <Field type="text" name="name" />
        <ErrorMessage name="name" component="div" />
        <Field type="email" name="email" />
        <ErrorMessage name="email" component="div" />
        <button type="submit">Submit</button>
    </Form>
</Formik>