728x90
react-hook-form 사용의 경우
import { useForm } from "react-hook-form";
const Login:React.FC = () => {
//Validation is triggered on the changeevent for each input, leading to multiple re-renders. Warning: this often comes with a significant impact on performance.
const { register, formState:{ errors },handleSubmit, formState, getValues } = useForm<ILoginForm>({mode: "onChange"});
const [token, setToken] = useRecoilState(tokenState)
const [user, setUserId] = useRecoilState(userIdState)
const [pwErrorMsg, setPwErrorMsg] = useState("");
const history = useHistory();
const onInvalid = (data:any) => {
//유효하지 않으면 실행
console.log(data, "onInvalid");
}
const onValid = async (data:ILoginForm) => {
//유효시 실행
try {
} catch (e) {
console.error(e);
}
}
return (
<div className="m-5">
<HelmetProvider>
<Helmet>
<title>Trader | Login</title>
</Helmet>
</HelmetProvider>
<h4 className="w-full font-medium text-left text-3xl mb-5">
Welcom to Trade
</h4>
<form
className="grid gap-2 w-full "
//🌟handleSubmit은 '새로고침을 하지 않는다' 즉, event.preventDefault()가 실행됨🌟
onSubmit={handleSubmit(onValid, onInvalid)}
>
<input
{...register("email", {
required: "Email is required",
pattern: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
})}
placeholder="Email"
className="input mb-3 focus:border-pink-400"
type="email"
/>
{errors.email?.message && (
<FormError errorMessage={errors.email.message} />
)}
{errors.email?.type === "pattern" && (
<FormError errorMessage="Please enter a valid email" />
)}
<input
{...register("password", {required: "Password is required", minLength:10})}
type="password"
placeholder="Password"
className="input focus:border-pink-400"
/>
{errors.password?.message && (
<FormError errorMessage={errors.password.message}/>
)}
{errors.password?.type === "minLength" && (
<FormError errorMessage="Password must be more than 10"/>
)}
{"" ? <FormError errorMessage={pwErrorMsg}/> : null}
<Button
canClick={formState.isValid}
actionText={"Log In"}
/>
</form>
<div>
{token === '' ? <Link to="/create-account" className=" text-red-300 font-bold hover:underline "> Sign up for membership</Link> : null}
</div>
</div>
)
}
export default Login
728x90
'Typescript & React' 카테고리의 다른 글
React에서 실제 값은 변경 정상 하지만 화면은 변경 안됨 해결 (1) | 2024.06.18 |
---|---|
Typscript 문법 오류 (0) | 2024.06.14 |
SyntaxError: Unexpected end of JSON input (0) | 2024.02.15 |
useHistory에서 새로고침이 되지 않을 때 해결방안 (0) | 2024.02.03 |
this의 이해 (1) | 2024.01.21 |