github.com/oinume/lekcije@v0.0.0-20231017100347-5b4c5eb6ab24/frontend/src/components/setting/EmailForm.tsx (about) 1 import React, {useState} from 'react'; 2 import {type SubmitHandler, useForm} from 'react-hook-form'; 3 import {InputError} from '../InputError'; 4 5 type Props = { 6 readonly email: string; 7 readonly handleOnChange: (event: React.ChangeEvent<HTMLInputElement>) => void; 8 readonly handleUpdateEmail: (email: string) => boolean; 9 }; 10 11 type FormValues = { 12 email: string; 13 }; 14 15 const formValidationRules = { 16 required: {value: true, message: '入力してください'}, 17 maxLength: {value: 100, message: '100文字以内で入力してください'}, 18 }; 19 20 export const EmailForm: React.FC<Props> = ({email, handleOnChange, handleUpdateEmail}) => { 21 const { 22 register, 23 handleSubmit, 24 formState: {errors, isDirty, isValid}, 25 } = useForm<FormValues>({mode: 'onChange'}); 26 const emailField = register('email', { 27 ...formValidationRules, 28 onChange(event: React.ChangeEvent<HTMLInputElement>) { 29 event.preventDefault(); 30 handleOnChange(event); 31 }, 32 }); 33 34 const onSubmit: SubmitHandler<FormValues> = data => { 35 const success = handleUpdateEmail(email); 36 }; 37 38 return ( 39 <form 40 className="needs-validation" 41 onSubmit={handleSubmit(onSubmit)} 42 > 43 <h5>通知先メールアドレス</h5> 44 <div className="mb-3"> 45 <input 46 required 47 autoFocus 48 type="email" 49 className={`form-control ${errors.email ? 'is-invalid' : ''}`} 50 id="email" 51 placeholder="Email" 52 autoComplete="on" 53 value={email} 54 {...emailField} 55 /> 56 { errors.email && <InputError message={errors.email.message}/> } 57 </div> 58 <button 59 type="submit" 60 disabled={!isDirty || !isValid} 61 className="btn btn-primary" 62 > 63 変更 64 </button> 65 </form> 66 ); 67 };