react-hook-form์ ์ ์ฉํด๋ณด์ (feat. ํ์๊ฐ์ )
by ๋๋ถ๋react-hook-form ๋?
react-hook-form ์ฌ์ฉ์ ํ๋ฉด form์ ๋ ์ฝ๊ฒ ๋ง๋ค๊ธฐ ์ํ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ก, ์๋์ ๊ฐ์ ์ฅ์ ์ ๊ฐ์ง๋๋ค.
์ฅ์
- ๋ฐฐ์ฐ๊ธฐ ์ฝ๋ค
- ์ ํจ์ฑ ๊ฒ์ฌ์ ์ ์ฉํ๋ค.
- HTML ํ์ค์ ํ์ฉํ์ฌ ์์ ์ ์ธ ๊ธฐ๋ฅ์ ์ ๊ณตํ๋ค.
- ์ฌ ๋ ๋๋ง ํ์๋ฅผ ์ต์ํํ๋ค.
- ๊ตฌ์ฑ ์์๋ฅผ ์ฆ๊ฐ ๋ถ๋ฆฌํ์ฌ ๊ฐ์ ์ปดํฌ๋ํธ ๋ด ์์๋ค์ ์๋ฏธ ์๋ ์ฌ ๋ ๋๋ง์ ๋ง์์ค๋ค.
- ์ ์ฒด ์์์ ์ฌ ๋ ๋๋ง ํ์ง ์๊ณ , ๊ฐ๋ณ ์ ๋ ฅ ๋ฐ ์์ ์ํ ์ ๋ฐ์ดํธ๋ฅผ ๊ตฌ๋ ํ ์ ์๋ค.
์ฌ๊ธฐ์๋ ๊ฐ๋ตํ๊ฒ ์ค๋ช ํ๊ณ ๋์ด๊ฐ๋๋ก ํ๊ฒ ์ต๋๋ค. ๋ ์์ธํ ๋ด์ฉ์ https://react-hook-form.com/ ์ ์ฐธ๊ณ ํด์ฃผ์ธ์.
react-hook-form ์ค์นํ๊ธฐ
์๋ ๋ช ๋ น์ด๋ฅผ ์ ๋ ฅํ๋ฉด, react-hook-form์ด ์ค์น๋์ด ์ฌ์ฉํ ์ ์์ต๋๋ค.
npm install react-hook-form
๊ฐ๋จํ ํ์๊ฐ์ ๋ง๋ค์ด๋ณด๊ธฐ
๊ฐ๋จํ ํ์๊ฐ์ ์ ํตํด react-hook-form์ ์ฌ์ฉํด ๋ณด๋๋ก ํ๊ฒ ์ต๋๋ค. ์ฐธ๊ณ ๋ก, css ์ฝ๋๋ ์๋ต๋์ด ์์ต๋๋ค.
import {useForm} from "react-hook-form";
const Signup = () => {
const {handleSubmit, register, formState: {errors}} = useForm();
function handleFormSubmit(values) {
console.log("values : ", values);
}
return (
<>
<div id="signupWrapper">
<div className="title text-2xl">ํ์๊ฐ์
</div>
<form className="form-submit" onSubmit={handleSubmit(handleFormSubmit)}>
<label>
์ด๋ฉ์ผ(ID)
<input type="email" name="email" {...register("email", {
required: "์ด๋ฉ์ผ์ ์
๋ ฅํด์ฃผ์ธ์.",
pattern: {
value: /[a-z0-9]{2,}@[a-z0-9-]{2,}\\.[a-z0-9]{2,}/i,
message: "์ด๋ฉ์ผ ํ์์ ๋ง๊ฒ ์
๋ ฅํด์ฃผ์ธ์."
}
})}/>
<span>{errors?.email?.message}</span>
</label>
<label>
๋น๋ฐ๋ฒํธ(PW)
<input type="password" name="password" {...register("password", {
required: "๋น๋ฐ๋ฒํธ๋ฅผ ์
๋ ฅํด์ฃผ์ธ์.",
pattern: {
value: /^(?=.*[A-Za-z])(?=.*\\d)(?=.*[!@#$%?*])[A-Za-z\\d@$!%*#?&]{8,}$/,
message: "์๋ฌธ์, ์ซ์ ๋ฐ ํน์๋ฌธ์(!@#$%?*)๋ฅผ ํฌํจํ์ฌ 8์๋ฆฌ ์ด์ ์
๋ ฅํด์ฃผ์ธ์."
}
})}/>
<span>{errors?.password?.message}</span>
</label>
<label>
์ด๋ฆ
<input type="name" name="name" {...register("name", {
required: "์ด๋ฆ์ ์
๋ ฅํด์ฃผ์ธ์."
})}/>
<span>{errors?.name?.message}</span>
</label>
<label>
ํธ๋ํฐ๋ฒํธ
<input type="phone" name="phone" {...register("phone", {
required: "ํธ๋ํฐ๋ฒํธ๋ฅผ ์
๋ ฅํด์ฃผ์ธ์.",
pattern: {
value: /^\\d{3}-\\d{3,4}-\\d{4}$/,
message: "000-0000-0000 ํ์์ผ๋ก ์
๋ ฅํด์ฃผ์ธ์."
}
})}/>
<span>{errors?.phone?.message}</span>
</label>
<label>
๋๋ค์
<input type="nickname" name="nickname" {...register("nickname", {
required: "๋๋ค์์ ์
๋ ฅํด์ฃผ์ธ์."
})}/>
<span>{errors?.nickname?.message}</span>
</label>
<div className="daangn-wrapper">
<button className="btn-daangn" type="submit">๊ฐ์
ํ๊ธฐ</button>
</div>
</form>
</div>
</>
)
}
export default Signup;
์๋ ์ด๋ฏธ์ง๋ฅผ ํตํด ์ ๋ ฅ์ ์ ๋๋ก ํ๋ฉด ๋๋ค์ ์ ๋ ฅ์ฐฝ์ฒ๋ผ ์๋ฌ ๋ฉ์์ง๊ฐ ๋จ์ง ์๊ณ , ํ์ ์ ๋ ฅ์ ์ฑ์ฐ์ง ์๊ฑฐ๋ ์ ํจํ์ง ์์ ๋ฐฉ์์ผ๋ก ์ ๋ ฅํ๋ฉด ์๋ฌ ๋ฉ์์ง๊ฐ ๋จ๋ ๊ฒ์ ํ์ธํ ์ ์์ต๋๋ค.
์ฐธ๊ณ
๋ธ๋ก๊ทธ์ ์ ๋ณด
๋๋ถ๋์ Devlog
๋๋ถ๋