#6.2 Introduction to Recoil part One/Two #6.6 Forms #6.7 Form Validation #6.8 Form Errors #6.9 Custom Validation

SilverAsh·2023년 10월 19일
0

React

목록 보기
10/16

interface IRouterProps {
    toggleDark: () => void
}

Global State
어플리케이션 전체에서 공유되는 state
☞traveling props problem

How to modify the value of the atom?

useSetRecoilState

React-Hook-Form 쓰지 않을 시

function ToDoList() {
    const [toDo, setToDo] = useState("")
    const onChange = (event: React.FormEvent<HTMLInputElement>) => {
        const { currentTarget: { value }, } = event;
        setToDo(value)
    }
    const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault();
        console.log(toDo)
    }
    return <div>
        <form onSubmit={onSubmit}>
            <input type="text" value={toDo} onChange={onChange} placeholder="Write a to do" />
            <button>Add</button>
        </form>
    </div>
}

위와 같은 경우, input이 더 생기면 늘어난 만큼의 state와 onChange함수들을 더 만들어줘야함, more validation too => use Library !
input의 바깥쪽 클릭 => onBlur

React-Hook-Form

 function ToDoList() {
    const { register, watch } = useForm();
    console.log(register("toDo"))
    return <div>
        <form action="">
            <input {...register("toDo")} type="text" placeholder="Write a to do" />
            <button>Add</button>
        </form>
    </div>
}

register 하나로 onchange, useState, value 모두 대체=> 효율적
watch는 form의 입력값들의 변화를 관찰할 수 있게 해주는 함수

Form Validation / Custom Validation

handleSubmit => validation 담당, 1 argument required (what to execute when data is validated)
아래 required는 html이 아닌 자바스크립트를 사용하여 validation
formState.errors => error handling
setError => trigger specific error
옵션 validate 함수/ 객체 모두 가능 (async function으로 해서 서버에서 확인을 받을 수도 있다,,)
setValue => useful after submitted

interface IForm {
    email: string;
    firstName: string;
    lastName: string;
    Username: string;
    Password: string;
    Password1: string;
     extraError?: string;
}
function ToDoList() {
    const { register, handleSubmit, formState: { errors }, setError } = useForm<IForm>({
        defaultValues: {
            email: "@naver.com"
        }
    });
    const onValid = (data: IForm) => {
        if (data.Password !== data.Password1) {
            setError("Password1", { message: "Password are not the same." }, { shouldFocus: true })
        } setError("extraError", { message: "Server offline" });
        setValue("(비우고싶은항목)","");
    }
    console.log(formState.errors)
       return <div>
        <form style={{ display: "flex", flexDirection: "column" }} onSubmit={handleSubmit(onValid)}>
            <input {...register("email", {
                required: "Email is required", pattern: {
                    value: /^[A-Za-z0-9._%+-]+@naver.com$/,
                    message: "only naver.com emails allowed"
                }
            })} placeholder="Email" />
            <span>{errors?.email?.message}</span>
            <input {...register("firstName", { required: true, validate: (value) => !value.includes("nico")
            // value.includes("nico") ? "no nicos allowed" : true 도 가능
            })} placeholder="First Name" />
            <input {...register("lastName", { required: true, validate: {
                    noNico: (value) => value.includes("nico") ? "no nicos allowed" : true,
                    noNick: (value) => value.includes("nick") ? "no nicks allowed" : true,
                } })} placeholder="Last Name" />
            <input {...register("Username", { required: true, minLength: 10 })} placeholder="Username" />
            <input {...register("Password", { required: "Password is Required", minLength: 5 })} placeholder="Password" />
            <input {...register("Password1", { required: true, minLength: 5 })} placeholder="Password1" />
            <button>Add</button>
        </form>
    </div>
}


profile
Frontend developer이자

0개의 댓글