Form Handling and Controlled Components in React JS

In React, form handling can be approached using controlled components. A controlled component is an input element whose value is controlled by the React state. The main idea behind controlled components is that the value of the input field is set through the component’s state, and any changes made to the input field will trigger an update to the state.

What are Controlled Components?

In React, controlled components are form elements such as <input>, <textarea>, or <select> elements where React takes control of their state. In other words, React is the single source of truth for the input values. Whenever the value of an input changes, it triggers an event that updates the React state, keeping the UI and the state in sync.

Example of a Controlled Component

          
              import React, { useState } from 'react';

              function ControlledForm() {
                  const [inputValue, setInputValue] = useState('');

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

                  const handleSubmit = (event) => {
                      event.preventDefault();
                      alert('Submitted: ' + inputValue);
                  };

                  return (
                      
); } export default ControlledForm;

In the example above, the <input> field is a controlled component because its value is set by the React state inputValue, which is updated through the handleChange function. The handleSubmit function prevents the default form submission behavior and shows an alert with the current input value.

Why Use Controlled Components?

Using controlled components offers several advantages:

  • Single Source of Truth: React state is the only source of truth for form data, making it easier to manage and debug the form data.
  • Real-time Validation: You can perform validation or transformation on input values before they are submitted, as the state is always up to date.
  • Easy to Handle Complex Forms: When working with forms that contain multiple inputs, using controlled components allows you to easily synchronize and manage the state of all form fields.

Handling Multiple Inputs in a Form

For forms with multiple input fields, you can manage their values using a single state object. This helps reduce redundancy and keeps the form more organized.

Example of Multiple Controlled Inputs

          
              import React, { useState } from 'react';

              function MultipleInputsForm() {
                  const [formData, setFormData] = useState({
                      firstName: '',
                      lastName: ''
                  });

                  const handleChange = (event) => {
                      const { name, value } = event.target;
                      setFormData({
                          ...formData,
                          [name]: value
                      });
                  };

                  const handleSubmit = (event) => {
                      event.preventDefault();
                      alert(`Submitted: ${formData.firstName} ${formData.lastName}`);
                  };

                  return (
                      
); } export default MultipleInputsForm;

In this example, we manage multiple form inputs using a single state object formData. The handleChange function updates the appropriate field based on the name attribute of each input field.

Uncontrolled Components

While controlled components are preferred in React, there are also uncontrolled components, where React does not manage the form input's state. Instead, you interact with the DOM directly using references (via ref) to read the values of input fields. Uncontrolled components can be useful in certain situations where you need to integrate with non-React code or when the form is simple and does not require dynamic state updates.

Example of Uncontrolled Component

          
              import React, { useRef } from 'react';

              function UncontrolledForm() {
                  const inputRef = useRef();

                  const handleSubmit = (event) => {
                      event.preventDefault();
                      alert('Submitted: ' + inputRef.current.value);
                  };

                  return (
                      
); } export default UncontrolledForm;

In the uncontrolled component example, the form input value is not bound to React state. Instead, we use useRef to get a reference to the DOM element, and then access its value directly when the form is submitted.

Controlled vs. Uncontrolled Components

While both controlled and uncontrolled components have their place in React development, controlled components are generally preferred because they provide greater control and flexibility. With controlled components, you can easily manipulate input values, apply validation, and manage form data more effectively.

Conclusion

In React, form handling with controlled components is a powerful technique for managing form inputs and state. By binding form elements to React state, you ensure that the form data is always synchronized with the component’s state, making it easier to handle complex forms, validate inputs, and respond to user actions. While uncontrolled components can be useful in certain scenarios, controlled components are the go-to choice for most React applications.





Advertisement