Home  >  Article  >  Web Front-end  >  React Design Patterns~Container Componets / Uncontrolled Controlled Component~

React Design Patterns~Container Componets / Uncontrolled Controlled Component~

Barbara Streisand
Barbara StreisandOriginal
2024-09-24 06:15:02671browse

React Design Patterns~Container Componets / Uncontrolled Controlled Component~

  • Uncontrolled Component

This pattern means that React doesn't control the form data, and the DOM holds the form state.

When you access the DOM, you must set the ref attribute using the useRef hook.

・src/components/uncontrolled-form.jsx

import React from "react";

export const UncontrolledForm = () => {
  const nameInputRef = React.createRef();
  const ageInputRef = React.createRef();

  console.log("renedering");

  const SubmitForm = (e) => {
    console.log(nameInputRef.current.value);
    console.log(ageInputRef.current.value);

    e.preventDefault();
  };

  return (
    <form onSubmit={SubmitForm}>
      <input name="name" type="text" placeholder="Name" ref={nameInputRef} />
      <input name="age" type="number" placeholder="Age" ref={ageInputRef} />
      <input type="submit" value="Submit" />
    </form>
  );
};
  • Controlled Component

This pattern means that React controls the form data using the useState hook.

We can fully control the input value and update it in real time.

import React, { useEffect, useState } from "react";

export const ControlledForm = () => {
  const [errorMessage, setErrorMessage] = useState("");
  const [name, setName] = useState("");
  const [age, setAge] = useState();

  useEffect(() => {
    if (name.length < 1) {
      setErrorMessage("name can not be empty");
    } else {
      setErrorMessage("");
    }
  }, [name]);

  return (
    <form>
      {errorMessage&& <p>{errorMessage}</p>}
      <input
        type="text"
        name="name"
        placeholder="Name"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
      <input
        type="number"
        name="age"
        placeholder="Age"
        value={age}
        onChange={(e) => setAge(e.target.value)}
      />
      <button>Submit</button>
    </form>
  );
};

The above is the detailed content of React Design Patterns~Container Componets / Uncontrolled Controlled Component~. 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