React Design Patterns~Container Componets / Uncontrolled Controlled Component~

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 (
    
); };
  • 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 (
    
{errorMessage&&

{errorMessage}

} setName(e.target.value)} /> setAge(e.target.value)} />
); };
Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post

Book: The C Programming Language

Next Post
server-side-rendering-(ssr):-uma-solucao-para-seo-e-performance-em-aplicacoes-react

Server-Side Rendering (SSR): Uma Solução para SEO e Performance em Aplicações React

Related Posts
役員変更登記

役員変更登記

2025-05-08 申請用総合ソフトで行う アカウントは個人で OK(法人用は特にない) 登記申請書(法人等用)を使う 参考 https://www.touki-kyoutaku-online.moj.go.jp/toukinet/taiken/taiken_zeninjuunin.html https://houmukyoku.moj.go.jp/homu/shogyo_online03.html 法人番号で検索した住所のハイフンが外字扱いだったので、直接入力に切り替えて入力した 電話がかかってきて以下のような文言修正を要求された 添付ファイルに電子署名が必要 議事録の「第 2 号議案:代表理事の重任について」を「第 2 号議案:理事及び代表理事の重任について」 同様に「任期満了に伴い、鈴木健志を理事及び代表理事に再任することを決議した。」 「なお席上就任を承諾した。」の文言を追加。同意書なしのため必要らしい。…
Read More