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