Engineering

React Forms: Controlled & Uncontrolled Methods Explained

-By Priya Nair

In the world of React, forms are primarily managed through two approaches: controlled and uncontrolled forms. Grasping the nuances of these two can aid you in seamlessly handling forms within your React projects. This guide will delve deep into both strategies, providing clear examples to facilitate well-informed decisions in your development process.

Controlled Forms

Controlled forms in React are overseen by the state property of a component, which is updated through the setState() function. An input element morphs into a controlled element when it is assigned a value and attached to a setState event. Essentially, React governs the element and dictates the outcomes of any user inputs, establishing a single source of truth.

 

Consider the scenario where an element is attributed with a value property:

<input type=“text” value=“”/>

 

Here, the input field is uneditable in the browser, showcasing React’s control over it. To modify this, alter the property value to defaultValue. Despite this, you still necessitate a way to fetch the value, which can be achieved using the useState hook to establish the input's state.

 

Here's an illustrative example:

 

import React, { useState } from 'react';

function ControlledForm() {

 const [num, setNum]= useState('');

 

 const handleNameChange = (e) => {

  setNum(e.target.value);

 };

 

 return (

   <div>

    <h2>Controlled Form Example</h2>

     <form>

       <label>

         Number:

         <input

          type="text"

          value={num}

          onChange={handleNameChange}

         />

       </label>

     </form>

     <p>Number entered: {num}</p>

   </div>

 );

}

 

export default ControlledForm;

 

In the above script, React monitors the input field's value through the state variable, "num", and all changes are recorded via the onChange event handler.

Uncontrolled Forms

Unlike controlled forms, uncontrolled forms operate independently of the React state, relying instead on the DOM itself. This strategy utilizes ‘ref’ to pinpoint specific DOM elements. Below is as implistic representation of uncontrolled forms:

 

import React, { useRef } from "react";

function UncontrolledEx() {

 const num =useRef(null);

 const item = (e)=> {

  e.preventDefault();

  console.log(num.current.value);

 };

 return (

   <div>

     Hello, number is here:

     <input ref={num} type="number" />

     <button onClick={item}>Button</button>

   </div>

 );

}

 

In this fragment, the useRef hook refers to an element in the DOM. Another depiction using the FormData API to access elements by their name properties is illustrated below:

 

function UncontrolledEx() {

 const item = (e)=> {

  e.preventDefault();

   const formData =new FormData(e.target);

   const num =formData.get('num');

   console.log(num);

 };

 

 return (

   <div>

     Hello, the counter is here:

     <form onSubmit={item}>

       <input name="num" type="number" />

       <button type="submit">Submit</button>

     </form>

   </div>

 );

}

 

Note that utilizing FormData necessitates the allocation of a name property to the form elements.

The Grand Dilemma: When to Use Which

Are you Team Controlled or Team Uncontrolled? Let’s break it down:

Controlled Forms

Uncontrolled Forms

Conclusion

Although controlled forms are generally advocated by React for most scenarios, there are circumstances where uncontrolled forms prevail, offering enhanced performance. Determining the right approach hinges on the specific needs of your project. For instance, a search functionality might not necessitate a two-way data binding to govern the form; awaiting user submission before gathering and transmitting data to the API might suffice. By mastering both controlled and uncontrolled forms, you empower yourself to craft versatile and efficient React applications.

Happy coding!

You may also like