DEV Community

Cover image for React Controlled/Uncontrolled Components
Mursal Furqan Kumbhar
Mursal Furqan Kumbhar

Posted on

React Controlled/Uncontrolled Components

In React, there are two main approaches to handling form inputs:

  • Controlled Components
  • Uncontrolled Components

Controlled Components provide more control and validation, while uncontrolled components are simpler and useful for basic forms of intermittent value access.

Controlled Components

These are form inputs whose values are controlled by React State. The state variables are updated whenever the value of the input changes, and the value of the input is set explicitly through the value prop.

The onChange event handler is used to update the state.

import React, { useState } from "react";
function ControlledComponent() {
     const [name, setName] = useState("")

     const handleChange = (e) => {
          setName(e.target.value);
     }

     return(
          <input
               type="text"
               value={name}
               onChange={handleChange}
          />
     );
}
Enter fullscreen mode Exit fullscreen mode

In the above example, the name state variable controls the input field's value. The handleChange function updates the name state whenever the input value changes and the input value is set to the Current value of the name state variable through the value prop.

Uncontrolled Components

Uncontrolled Components are form inputs that manage their state internally, rather than being controlled by React State. You can access the current value of the input using a ref after the form is submitted or whenever needed.

import React, { useRef } from "react";
function UncontrolledComponent() {
     const inputRef = useRef(null);

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

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

In this above example, the inputRef is used to create a ref for the input field. The handleSubmit function accesses the current value of the input using inputRef.current.value. The form submission logic can be implemented to utilize the input value as required.

Top comments (1)

Collapse
 
makamemawe profile image
makamemawe

What the best approach between controlled and uncontrolled