관리 메뉴

Silver Library (Archived)

미궁의 react hook form, 대체 어떻게 전달될까. 본문

F5. Library of Tools/React.js

미궁의 react hook form, 대체 어떻게 전달될까.

Chesed Kim 2023. 2. 25. 21:03
반응형

특징이 있다면, register, 그리고 onSubmit, handleSubmit. 이렇게 자주 쓰인다는 점.

 

그리고 이걸, onSubmit 으로 보내주는 건지, 진짜 어마어마한 미궁이라는 생각이 들었습니다.

도대체 엮은 것도 없는데, 무슨 재주로 저걸 const 변수 선언 영역에서 참조하는 state 변수명 지정도 없이 바로 버튼을 인식 해서 그렇게 바로 patch request 가 전송되는지.

 

CRUD 또한 이해하고 있고, 그렇다면 남은건...react hook form 이다는 점.

그러던 중, 이 글을 발견했습니다.

편리한 input 다루기 - React Hook Form (velog.io)

 

편리한 input 다루기 - React Hook Form

yarn add react-hook-form@6 (현재 7버젼까지 나왔음, 개인적으로는 아직 6이 편함)밑에는 회원가입 폼이지만, 대부분의 input 요소에 사용하면 좋은 라이브러리.select 느 radio 도 react-hook-form 으로 될 뿐 아

velog.io

This is a React component named register that defines a form for user registration. It uses the useState and useRef hooks from React to manage state and refs, respectively. It also uses the useForm hook from the react-hook-form library to handle form validation and submission.

 

The form has several input fields for the user's name, email, phone number, password, and password confirmation. Each input field has its own validation rules specified in the ref attribute using the register function from react-hook-form. The validation rules check for required fields, proper formatting, and password complexity.

 

The form also includes a submit button that is disabled when the loading state is true. When the form is submitted, the onSubmit function is called, which sends a POST request to an API endpoint using the axios library. If the request is successful, the response is logged to the console. If the request fails, an error message is displayed using the alert function.

 

Overall, this component provides a basic user registration form with client-side form validation and server-side data submission.

import React, { useState, useRef } from "react";
import { useForm } from "react-hook-form";
import axios from "axios";

function register() {
  const { register, watch, errors, handleSubmit } = useForm(); // useForm({ mode: "onChange" });
  // console.log(watch("email"));
  const userpwd = useRef();
  userpwd.current = watch("userpwd");

  const [loading, setLoading] = useState(false);

  const onSumit = async (data) => {
    setLoading(true);
    console.log(data);
    const { email, name, userpwd, phone } = data;
    try {
      const response = await axios.post("/api/user/user", {
        email,
        name,
        userpwd,
        phone,
      });
      console.log(response);
    } catch (error) {
      alert(error.response.data);
    }
    setLoading(false);
  };
  return (
    <div style={{ width: "1024px", margin: "50px auto" }}>
      <form onSubmit={handleSubmit(onSumit)}>
        <label>Name</label>
        <input
          name="name"
          type="text"
          placeholder="EX) 홍길동"
          ref={register({
            required: true,
            pattern: /^[가-힣]{2,7}$/,
          })}
        />
        {errors.name && errors.name.type === "required" && (
          <p>이름을 입력해주세요.</p>
        )}
        {errors.name && errors.name.type === "pattern" && (
          <p>이름 형식에 맞지 않습니다. 한글로 올바르게 이름을 입력해주세요.</p>
        )}
        <label>Email</label>
        <input
          name="email"
          type="email"
          placeholder="EX ) mindcrying@naver.com"
          ref={register({
            required: true,
            pattern:
              /^[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*.[a-zA-Z]{2,3}$/i,
          })}
        />
        {errors.email && <p>이메일을 입력해주세요.</p>}
        <label>Phone</label>
        <input
          name="phone"
          type="number"
          placeholder="연락처는 숫자로만 입력해주세요. ex) 01012345678"
          ref={register({
            required: true,
            pattern: /(^02.{0}|^01.{1}|[0-9]{3})([0-9]+)([0-9]{4})/g,
          })}
        />
        {errors.phone && (
          <p>연락처는 01012345678 처럼 숫자로만 입력해주세요.</p>
        )}
        <label>Password</label>
        <input
          name="userpwd"
          type="password"
          ref={register({
            required: true,
            pattern:
              /(?=.*\d{1,50})(?=.*[~`!@#$%\^&*()-+=]{1,50})(?=.*[a-zA-Z]{2,50}).{8,16}$/,
          })}
        />
        {errors.userpwd && errors.userpwd.type === "required" && (
          <p>비밀번호를 입력해주세요.</p>
        )}
        {errors.userpwd && errors.userpwd.type === "pattern" && (
          <p>
            비밀번호는 8~16자로 영문 소문자, 숫자, 특수기호를 조합해서
            사용하세요.
          </p>
        )}

        <label>Password Confirm</label>
        <input
          name="userpwd_confirm"
          type="password"
          ref={register({
            required: true,
            validate: (value) => value === userpwd.current,
          })}
        />
        {errors.userpwd_confirm &&
          errors.userpwd_confirm.type === "required" && (
            <p>비밀번호 확인을 해주세요.</p>
          )}
        {errors.userpwd_confirm &&
          errors.userpwd_confirm.type === "validate" && (
            <p>비밀번호가 일치하지 않습니다.</p>
          )}
        <input type="submit" disabled={loading} />
      </form>
    </div>
  );
}

export default register;

Bonus. Why used ref in here?

In React, a ref is a way to access the properties or methods of a React component or HTML element. Refs are typically used to get a reference to an input field, an instance of a component, or to modify the behavior of a child component from its parent.

In the register component shown in the example, a ref is used to get the value of the userpwd input field when the user types in the userpwd_confirm input field. This is achieved by creating a userpwd ref using the useRef hook and setting it equal to the current value of the userpwd input field using the watch function from react-hook-form.

 

The userpwd ref is then passed as an argument to the validate function for the userpwd_confirm input field using the register function from react-hook-form. This allows the validate function to compare the value of the userpwd_confirm input field with the current value of the userpwd ref and return an error message if they do not match.

 

Using a ref in this way enables us to compare the value of two input fields in real-time without needing to submit the form first. This is a common use case for refs in React and is useful for implementing features such as password confirmation fields, where the user needs to type in their password twice to confirm it.

 

'F5. Library of Tools > React.js' 카테고리의 다른 글

Crash note - list, key, fake data generator  (0) 2023.01.28
So, how to useEffect?  (0) 2023.01.11
OOP, but how with reactjs?  (0) 2023.01.11