0

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.

1 Answer 1

1

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) 

Edit Q-57648264-FormSubmit

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.