Home  >  Article  >  Web Front-end  >  React Controlled/Uncontrolled Components

React Controlled/Uncontrolled Components

WBOY
WBOYOriginal
2024-09-03 22:42:32774browse

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

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

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.

The above is the detailed content of React Controlled/Uncontrolled Components. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn