How to validate form using react hooks ?
I used class components and it worked great, but now decided to use functional components with hooks and don't know the best way to validate form. My code:
const PhoneConfirmation = ({ onSmsCodeSubmit }) => {
const [smsCode, setSmsCode] = useState('');
const onFormSubmit = (e) => {
e.preventDefault();
if (smsCode.length !== 4) return;
onSmsCodeSubmit(smsCode);
}
const onValueChange = (e) => {
const smsCode = e.target.value;
if (smsCode.length > 4) return;
setSmsCode(smsCode);
};
return (
<form onSubmit={onFormSubmit}>
<input type="text" value={smsCode} onChange={onValueChange} />
<button type="submit">Submit</button>
</form>
)
};
It works but I don't think it's good idea to use handler function inside functional component, because it will be defined every time when the component is called.