https://blog.bitsrc.io/react-hook-form-vs-formik-form-builder-library-for-react-23ed559fdae 정리함
const handleChange = ({ target }) => {
const { formValues } = formState;
formValues[target.name] = target.value;
setFormState({ formValues });
handleValidation(target);
};
const [formState, setFormState] = useState({
formValues: {
email: "",
password: ""
},
formErrors: {
email: "",
password: ""
},
formValidity: {
email: false,
password: false
}
});
<input name="firstName" onChage={handleChange} />
const handleChange = ({target}) => {
const { formValues } = formState;
formValues[target.name] = target.value;
setFormState({ formValues });
handleValidation(target);
};
const handleSubmit = event => {
event.preventDefault();
const { formValues, formValidity } = formState;
if (Object.values(formValidity).every(Boolean)) {
// Form is valid
console.log(formValues);
} else {
for (let key in formValues) {
let target = {
name: key,
value: formValues[key]
};
handleValidation(target);
}
}
};
https://bit.dev/nsebhastian/tutorial-examples/react-formik-example?example=5ee39cf3c166fb0019182911
function validateEmail(value) {
let error;
if (!value) {
error = "Email is required";
} else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value)) {
error = "Invalid email address format";
}
return error;
}
function validatePassword(value) {
let error;
if (!value) {
error = "Password is required";
} else if (value.length < 3) {
error = "Password must be 3 characters at minimum";
}
return error;
}
register
란 ref props이다. 이건 검증과 제출을 쉽게 해준다.