简体   繁体   中英

How to validate form using react hooks?

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.

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) 

编辑 Q-57648264-FormSubmit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM