React Forms

Introduction

In this chapter, we will explore how to work with forms in React. Forms are essential for collecting user input and handling it in a controlled manner. We will cover the basics of form handling, focusing on key form controls like input, checkbox, radio, and select elements. We will start with examples using class components and then cover the same using functional components.

Table of Contents

  1. Basics of React Forms
  2. Controlled Components
    • Example: Input Field
  3. Handling Different Form Controls
    • Example: Checkbox
    • Example: Radio Buttons
    • Example: Select Dropdown
  4. Using Class Components
    • Example: Complete Form with Class Components
  5. Using Functional Components
    • Example: Complete Form with Functional Components
  6. Key Features of React Forms
  7. Conclusion

Basics of React Forms

Forms in React are similar to forms in HTML, but they are controlled by React state. This means that the form data is managed by the React component rather than the DOM. This allows you to have full control over the form’s data and behavior.

Controlled Components

Controlled components are form elements whose value is controlled by the state of a React component. This means that the form element’s value is determined by the component’s state, and any changes to the form element will update the component’s state.

Example: Input Field

Let’s start with a basic example of an input field using a class component.

  1. Create a New File for the Component: In the src directory, create a new file named InputFieldClass.js.

  2. Define the Component: Add the following code to InputFieldClass.js to create a controlled input component:

    // InputFieldClass.js
    import React, { Component } from 'react';
    
    class InputFieldClass extends Component {
      constructor(props) {
        super(props);
        this.state = {
          inputValue: ''
        };
      }
    
      handleChange = (event) => {
        this.setState({ inputValue: event.target.value });
      };
    
      render() {
        return (
          <div>
            <h1>Controlled Input</h1>
            <input
              type="text"
              value={this.state.inputValue}
              onChange={this.handleChange}
            />
            <p>Current Value: {this.state.inputValue}</p>
          </div>
        );
      }
    }
    
    export default InputFieldClass;
    

    Explanation:

    • The InputFieldClass component uses this.state to manage the value of the input field.
    • The handleChange method updates the state with the current value of the input field.
    • The value attribute of the input field is set to this.state.inputValue, making it a controlled component.
  3. Use the Component in App.js: Open src/App.js and modify the App component to use the InputFieldClass component:

    // App.js
    import React from 'react';
    import InputFieldClass from './InputFieldClass';
    
    function App() {
      return (
        <div>
          <InputFieldClass />
        </div>
      );
    }
    
    export default App;
    
  4. Save and View Changes: Save the files and go to your browser. You should see a controlled input field that updates the displayed value as you type.

Handling Different Form Controls

Example: Checkbox

  1. Create a New File for the Component: In the src directory, create a new file named CheckboxClass.js.

  2. Define the Component: Add the following code to CheckboxClass.js to create a controlled checkbox component:

    // CheckboxClass.js
    import React, { Component } from 'react';
    
    class CheckboxClass extends Component {
      constructor(props) {
        super(props);
        this.state = {
          isChecked: false
        };
      }
    
      handleChange = (event) => {
        this.setState({ isChecked: event.target.checked });
      };
    
      render() {
        return (
          <div>
            <h1>Controlled Checkbox</h1>
            <label>
              <input
                type="checkbox"
                checked={this.state.isChecked}
                onChange={this.handleChange}
              />
              Check me
            </label>
            <p>Checkbox is {this.state.isChecked ? 'checked' : 'unchecked'}</p>
          </div>
        );
      }
    }
    
    export default CheckboxClass;
    
  3. Use the Component in App.js: Open src/App.js and modify the App component to use the CheckboxClass component:

    // App.js
    import React from 'react';
    import CheckboxClass from './CheckboxClass';
    
    function App() {
      return (
        <div>
          <CheckboxClass />
        </div>
      );
    }
    
    export default App;
    
  4. Save and View Changes: Save the files and go to your browser. You should see a controlled checkbox that updates the displayed status as you check and uncheck it.

Example: Radio Buttons

  1. Create a New File for the Component: In the src directory, create a new file named RadioButtonsClass.js.

  2. Define the Component: Add the following code to RadioButtonsClass.js to create a controlled radio buttons component:

    // RadioButtonsClass.js
    import React, { Component } from 'react';
    
    class RadioButtonsClass extends Component {
      constructor(props) {
        super(props);
        this.state = {
          selectedOption: 'option1'
        };
      }
    
      handleChange = (event) => {
        this.setState({ selectedOption: event.target.value });
      };
    
      render() {
        return (
          <div>
            <h1>Controlled Radio Buttons</h1>
            <label>
              <input
                type="radio"
                value="option1"
                checked={this.state.selectedOption === 'option1'}
                onChange={this.handleChange}
              />
              Option 1
            </label>
            <label>
              <input
                type="radio"
                value="option2"
                checked={this.state.selectedOption === 'option2'}
                onChange={this.handleChange}
              />
              Option 2
            </label>
            <p>Selected option: {this.state.selectedOption}</p>
          </div>
        );
      }
    }
    
    export default RadioButtonsClass;
    
  3. Use the Component in App.js: Open src/App.js and modify the App component to use the RadioButtonsClass component:

    // App.js
    import React from 'react';
    import RadioButtonsClass from './RadioButtonsClass';
    
    function App() {
      return (
        <div>
          <RadioButtonsClass />
        </div>
      );
    }
    
    export default App;
    
  4. Save and View Changes: Save the files and go to your browser. You should see controlled radio buttons that update the displayed selected option as you change the selection.

Example: Select Dropdown

  1. Create a New File for the Component: In the src directory, create a new file named SelectDropdownClass.js.

  2. Define the Component: Add the following code to SelectDropdownClass.js to create a controlled select dropdown component:

    // SelectDropdownClass.js
    import React, { Component } from 'react';
    
    class SelectDropdownClass extends Component {
      constructor(props) {
        super(props);
        this.state = {
          selectedValue: 'option1'
        };
      }
    
      handleChange = (event) => {
        this.setState({ selectedValue: event.target.value });
      };
    
      render() {
        return (
          <div>
            <h1>Controlled Select Dropdown</h1>
            <select value={this.state.selectedValue} onChange={this.handleChange}>
              <option value="option1">Option 1</option>
              <option value="option2">Option 2</option>
              <option value="option3">Option 3</option>
            </select>
            <p>Selected value: {this.state.selectedValue}</p>
          </div>
        );
      }
    }
    
    export default SelectDropdownClass;
    
  3. Use the Component in App.js: Open src/App.js and modify the App component to use the SelectDropdownClass component:

    // App.js
    import React from 'react';
    import SelectDropdownClass from './SelectDropdownClass';
    
    function App() {
      return (
        <div>
          <SelectDropdownClass />
        </div>
      );
    }
    
    export default App;
    
  4. Save and View Changes: Save the files and go to your browser. You should see a controlled select dropdown that updates the displayed selected value as you change the selection.

Using Class Components

Example: Complete Form with Class Components

  1. Create a New File for the Component: In the src directory, create a new file named CompleteFormClass.js.

  2. Define the Component: Add the following code to CompleteFormClass.js to create a complete form component that includes input, checkbox, radio buttons, and select dropdown elements:

    // CompleteFormClass.js
    import React, { Component } from 'react';
    
    class CompleteFormClass extends Component {
      constructor(props) {
    
    
        super(props);
        this.state = {
          username: '',
          isSubscribed: false,
          gender: 'male',
          favoriteColor: 'red'
        };
      }
    
      handleChange = (event) => {
        const { name, value, type, checked } = event.target;
        this.setState({
          [name]: type === 'checkbox' ? checked : value
        });
      };
    
      handleSubmit = (event) => {
        event.preventDefault();
        alert(`Form submitted with the following data:
        Username: ${this.state.username}
        Subscribed: ${this.state.isSubscribed}
        Gender: ${this.state.gender}
        Favorite Color: ${this.state.favoriteColor}`);
      };
    
      render() {
        return (
          <div>
            <h1>Complete Form</h1>
            <form onSubmit={this.handleSubmit}>
              <label>
                Username:
                <input
                  type="text"
                  name="username"
                  value={this.state.username}
                  onChange={this.handleChange}
                />
              </label>
              <br />
              <label>
                Subscribe to newsletter:
                <input
                  type="checkbox"
                  name="isSubscribed"
                  checked={this.state.isSubscribed}
                  onChange={this.handleChange}
                />
              </label>
              <br />
              <label>
                Gender:
                <input
                  type="radio"
                  name="gender"
                  value="male"
                  checked={this.state.gender === 'male'}
                  onChange={this.handleChange}
                />
                Male
                <input
                  type="radio"
                  name="gender"
                  value="female"
                  checked={this.state.gender === 'female'}
                  onChange={this.handleChange}
                />
                Female
              </label>
              <br />
              <label>
                Favorite Color:
                <select
                  name="favoriteColor"
                  value={this.state.favoriteColor}
                  onChange={this.handleChange}
                >
                  <option value="red">Red</option>
                  <option value="blue">Blue</option>
                  <option value="green">Green</option>
                </select>
              </label>
              <br />
              <button type="submit">Submit</button>
            </form>
          </div>
        );
      }
    }
    
    export default CompleteFormClass;
    
  3. Use the Component in App.js: Open src/App.js and modify the App component to use the CompleteFormClass component:

    // App.js
    import React from 'react';
    import CompleteFormClass from './CompleteFormClass';
    
    function App() {
      return (
        <div>
          <CompleteFormClass />
        </div>
      );
    }
    
    export default App;
    
  4. Save and View Changes: Save the files and go to your browser. You should see a complete form with input, checkbox, radio buttons, and select dropdown elements. When you submit the form, it will display an alert with the form data.

Using Functional Components

The useState hook is used to manage state in functional components. For form handling, you can use useState to create state variables for each form control and update them with event handlers.

Example: Complete Form with Functional Components

  1. Create a New File for the Component: In the src directory, create a new file named CompleteFormFunction.js.

  2. Define the Component: Add the following code to CompleteFormFunction.js to create a complete form component using functional components and hooks:

    // CompleteFormFunction.js
    import React, { useState } from 'react';
    
    function CompleteFormFunction() {
      const [formData, setFormData] = useState({
        username: '',
        isSubscribed: false,
        gender: 'male',
        favoriteColor: 'red'
      });
    
      const handleChange = (event) => {
        const { name, value, type, checked } = event.target;
        setFormData((prevFormData) => ({
          ...prevFormData,
          [name]: type === 'checkbox' ? checked : value
        }));
      };
    
      const handleSubmit = (event) => {
        event.preventDefault();
        alert(`Form submitted with the following data:
        Username: ${formData.username}
        Subscribed: ${formData.isSubscribed}
        Gender: ${formData.gender}
        Favorite Color: ${formData.favoriteColor}`);
      };
    
      return (
        <div>
          <h1>Complete Form</h1>
          <form onSubmit={handleSubmit}>
            <label>
              Username:
              <input
                type="text"
                name="username"
                value={formData.username}
                onChange={handleChange}
              />
            </label>
            <br />
            <label>
              Subscribe to newsletter:
              <input
                type="checkbox"
                name="isSubscribed"
                checked={formData.isSubscribed}
                onChange={handleChange}
              />
            </label>
            <br />
            <label>
              Gender:
              <input
                type="radio"
                name="gender"
                value="male"
                checked={formData.gender === 'male'}
                onChange={handleChange}
              />
              Male
              <input
                type="radio"
                name="gender"
                value="female"
                checked={formData.gender === 'female'}
                onChange={handleChange}
              />
              Female
            </label>
            <br />
            <label>
              Favorite Color:
              <select
                name="favoriteColor"
                value={formData.favoriteColor}
                onChange={handleChange}
              >
                <option value="red">Red</option>
                <option value="blue">Blue</option>
                <option value="green">Green</option>
              </select>
            </label>
            <br />
            <button type="submit">Submit</button>
          </form>
        </div>
      );
    }
    
    export default CompleteFormFunction;
    
  3. Use the Component in App.js: Open src/App.js and modify the App component to use the CompleteFormFunction component:

    // App.js
    import React from 'react';
    import CompleteFormFunction from './CompleteFormFunction';
    
    function App() {
      return (
        <div>
          <CompleteFormFunction />
        </div>
      );
    }
    
    export default App;
    
  4. Save and View Changes: Save the files and go to your browser. You should see a complete form with input, checkbox, radio buttons, and select dropdown elements. When you submit the form, it will display an alert with the form data.

Key Features of React Forms

  1. Controlled Components: Forms in React are controlled by state, allowing you to manage the form data and behavior fully.
  2. Multiple Form Controls: React supports various form controls, including input fields, checkboxes, radio buttons, and select dropdowns.
  3. Event Handling: React provides straightforward event handling for form submission and input changes.
  4. Flexibility: Forms can be managed using both class components and functional components with hooks.

Conclusion

In this chapter, you learned how to work with forms in React, including handling different form controls like input fields, checkboxes, radio buttons, and select dropdowns. You also learned how to create complete forms using both class components and functional components with hooks. Understanding how to manage forms is essential for collecting and handling user input effectively in React applications. In the next chapter, we will explore more on how to work with forms in React using Functional Components.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top