"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > React Controlled/Uncontrolled Components

React Controlled/Uncontrolled Components

Published on 2024-11-09
Browse:613

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(
          
     );
}

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(
          
); }

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.

Release Statement This article is reproduced at: https://dev.to/mursalfk/react-controlleduncontrolled-components-55nk?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3