상세 컨텐츠

본문 제목

[React] React Hook Form

React

by 래모 2022. 7. 15. 18:59

본문

설치방법

npm install react-hook-form

 

이전 코드

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

function TodoList() {
     const [toDo, setToDo] = useState("");
    const [toDoError, setToDoError] = useState("")
    const onChange = (e: React.FormEvent<HTMLInputElement>) => {
        const {currentTarget: {value}} = e;
        setToDoError("");
        setToDo(value);
    }
    const onSubmit = (e:React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        if(toDo.length < 10){
            return setToDoError("To do should be longer")
        }
        console.log("sumbit")
    } 

    return (
        <div>
            <form onSubmit={onSubmit}>
                <input onChange = {onChange}placeholder="Write a to do" />
                <button>Add</button>
                {toDoError!=="" ? toDoError: null }
            </form>
        </div>
    )
}

export default TodoList;

 

이 후 

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

function TodoList() {
    const {register, watch, handleSubmit} = useForm();
    const onValid = (data:any) => {
        console.log(data)
    }
    return (
        <div>
            <form onSubmit={handleSubmit(onValid)}>
                <input {...register("toDo", {required:true, minLength: 10})} placeholder="Write a to do" />
                <button>Add</button>
            </form>
        </div>
    )
}

export default TodoList;

 

Register

: name, onBlur, onChange, onClick, ref를 return하는 함수

 

< input {...register("category") ... >라고 작성해주면 register 함수가 반환하는 객체를 input의 props로 사용할 수 있음

console.log(register("toDo")) 시 보이는 것


< input onSubmit={} onClick={} onBlur={} >를 대체 해준다.

Watch

: form 의 입력값들의 변화를 관찰하는 함수

onChange와 같은 역할을 한다.

console.log(watch())

 

handleSubmit

: onSubmit 이벤트를 대체해줌

form의 onSumbit에 handle

<form onSubmit={handleSubmit(onValid, onInValid)}>
</form>
  • onValid( 필수 ) : 데이터가 유효할 때 호출되는 함수
  • onInValid( 필수x ) : 데이터가 유효하지 않을 때 호출되는 함수

 

유효성 검사하는 방법

< input {...register("email",{required: true, minLength: 10})} />
// minLength는 최소 길이 검사

라고 작성하고 input에 값을 적지 않고 내보내면 

react-hook-form이 값이 유효한지 확인 후 오류가 있는 부분에 커서를 가져다 줌


여러 개로 작성해보자!

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

function TodoList() {
    const {register, watch, handleSubmit} = useForm();
    const onValid = (data:any) => {
        console.log(data)
    }
    return (
        <div>
            <form onSubmit={handleSubmit(onValid)}>
                <input {...register("email", { required: true })} placeholder="Email" />
                <input
                    {...register("firstName", { required: true })}
                    placeholder="First Name"
                />
                <input
                    {...register("lastName", { required: true })}
                    placeholder="Last Name"
                />
                <input
                    {...register("username", { required: true, minLength: 10 })}
                    placeholder="Username"
                />
                <input
                    {...register("password", { required: true, minLength: 5 })}
                    placeholder="Password"
                />
                <input
                    {...register("password1", { required: true, minLength: 5 })}
                    placeholder="Password1"
                />
                <button>add</button>
            </form>
        </div>
    )
}

export default TodoList;

 

 

formState

각 input에 일어난 error를 확인해주는 함수이다

const {formState:{errors}} = useForm();
console.log(errors);

⬅️전체에 아무것도 입력 되지 않았어!!라고 하는 오류 /// username,password,password1에 글자 수가 부족해!! 라고 하는 오류➡️

 

 

<input
    {...register("password1", {
    required: "Password is required",
    minLength: {
        value: 5,
        message: "Your password is too short.",
    },
    })}
    placeholder="Password1"
/>

required에 메세지를 적어주면 해당 메시지가 error가 발생시 보여진다.

minLength에는 value와 message를 적어줄 수 있슴

 

 

정규표현식

<input {...register("email", {
        required: true ,
        pattern: {
            value: /^[A-Za-z0-9._%+-]+@naver.com$/,
            message: "Only naver.com emails allowed",},
        })}
    placeholder="Email" />

^ :문장의 시작
[] : 문자셋 안의 아무문자
+ : 하나 또는 많이

 

setError

const {setError} = useForm();
const onValid = (data:any) => {
    if(data.password !== data.password1){
        setError("password1", {message: "Password are not the same"}, {shouldFocus: true})
    }
}

에러 메세지를 설정해줌

shoudFocus를 해주면 틀렸을 때 자동으로 포커스가 password1으로 감

 

 

<input
    {...register("firstName", { required: "write here" ,validate: {
        noNico: (value) =>value.includes("nico") ? "no nicos allowed" : true,
        noNick: (value) =>value.includes("nick") ? "no nick allowed" : true,}
    })}
    placeholder="First Name"
/>

input의 register에 validate를 넣어주면 함수로 value값에 대한 조건을 만들어줄 수 있음

 

 

reset

const {reset} = useForm();
reset()

말 그대로 데이터를 리셋시켜줌

 

https://react-hook-form.com/api/useform/reset

 

useForm - reset

Performant, flexible and extensible forms with easy-to-use validation.

react-hook-form.com

 

'React' 카테고리의 다른 글

[모각코][React] useQuery  (0) 2022.08.07
[React] Framer Motion  (0) 2022.07.20
[React] Recoil로 상태 관리 하기  (0) 2022.07.14
[React] ThemeProvider  (0) 2022.07.09
[React] Typescript로 React 작성하기  (0) 2022.07.06

관련글 더보기