Reputation: 1350
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.
Upvotes: 0
Views: 1154
Reputation: 53874
Your code is fine, but you can slightly improve it because you don't need a controlled component.
Moreover, you can memorize the component so it won't make unnecessary render on onSmsCodeSubmit
change due to its parent render.
const FORM_DATA = {
SMS: 'SMS'
}
const PhoneConfirmation = ({ onSmsCodeSubmit, ...props }) => {
const onSubmit = e => {
e.preventDefault();
const data = new FormData(e.target);
const currSmsCode = data.get(FORM_DATA.SMS);
onSmsCodeSubmit(currSmsCode);
};
return (
<form onSubmit={onSubmit} {...props}>
<input type="text" name={FORM_DATA.SMS} />
<button type="submit">Submit</button>
</form>
);
};
// Shallow comparison by default
export default React.memo(PhoneConfirmation)
Upvotes: 1