Back to all posts
React useForm custom
Written by ppotatoG & Posted on October 26th, 2022
로그인 페이지 & 회원가입 페이지 내 동일 폼 재사용을 위한 컴포넌트
input value handling
input
하단으로error message
노출isUser
사용으로 로그인 버튼 노출
// common/UseAuthForm.tsxexport default function UseAuthForm ({email,setEmail,password,setPassword,modalIsOpen,setIsOpen,modalText,onSubmit,isUser} : any){const [emailError, setEmailError] = useState<boolean>(false);const [emailErrorMessage, setEmailErrorMessage] = useState<string | ''>('');const [passwordError, setPasswordError] = useState<boolean>(false);const [passwordErrorMessage, setPasswordErrorMessage] = useState<string | ''>('');// input value handlingconst onChangeEmailCheck = (e: React.ChangeEvent<HTMLInputElement>) => {const {name, value} = e.target;setEmail(value);setEmailErrorMessage(validate(name, value));setEmailError(emailErrorMessage === '');};const onChangePasswordCheck = (e: React.ChangeEvent<HTMLInputElement>) => {const {name, value} = e.target;setPassword(value);setPasswordErrorMessage(validate(name, value));setPasswordError(passwordErrorMessage === '');};const validate = (type: string, str: string): string => {if (type === 'email') {if (!str) {return '이메일을 입력해주세요';} else if (!EmailPattern.test(str)) {return '올바른 이메일을 입력해주세요.';}} else if (type === 'password') {if (!str) {return '비밀번호를 입력해주세요';} else if (str.length < 8) {return '올바른 비밀번호를 입력해주세요';}}return '';};return (<form className={styles.auth} onSubmit={onSubmit}><div className={styles.auth__item}><label htmlFor='email'>이메일</label><inputtype="email"name="email"id="email"requiredvalue={email}onChange={onChangeEmailCheck}/></div>// error message{emailErrorMessage !== '' && <p className={styles.errorMessage}>{emailErrorMessage}</p>}<div className={styles.auth__item}><label htmlFor='password'>비밀번호</label><inputtype="password"name="password"id="password"requiredvalue={password}onChange={onChangePasswordCheck}/></div>// error message{passwordErrorMessage && <p className={styles.errorMessage}>{passwordErrorMessage}</p>}<div className={styles.btn_wrap}>// 회원가입 페이지에서 로그인 버튼 미노출{isUser &&<buttondisabled={!emailError || !passwordError}className={styles.btn_wrap__item}>로그인</button>}<a className={styles.btn_wrap__item} href="../auth/SignUp">회원가입</a></div>{modalIsOpen &&<CustomModaltext={modalText}modalIsOpen={modalIsOpen}setIsOpen={setIsOpen}/>}</form>)};
// SignUp.tsxconst SignUp: React.FC = () => {const [email, setEmail] = useState<string>('');const [password, setPassword] = useState<string>('');const [modalIsOpen, setIsOpen] = useState<boolean>(false);const [modalText, setModalText] = useState<string>('');const modalOpen = (text : string) => {setIsOpen(true);setModalText(text);}const onSubmit = async (e: React.FormEvent<HTMLFormElement>): Promise<void> => {e.preventDefault();axios.post('http://localhost:8080/users/create', {email: email,password: password}).then( response => {console.log(response)modalOpen(response.data.message);}).catch( error => {console.log(error)modalOpen(error.response.data.details);})}return (<UseAuthFormemail={email}setEmail={setEmail}password={password}setPassword={setPassword}modalIsOpen={modalIsOpen}setIsOpen={setIsOpen}onSubmit={onSubmit}modalText={modalText}setModalText={setModalText}isUser={false}/>)};
// SignIn.tsxconst SignIn: React.FC = () => {const [email, setEmail] = useState<string>('');const [password, setPassword] = useState<string>('');const [modalIsOpen, setIsOpen] = useState<boolean>(false);const [modalText, setModalText] = useState<string>('');const modalOpen = (text : string) => {setIsOpen(true);setModalText(text);}const onSubmit = async (e: React.FormEvent<HTMLFormElement>): Promise<void> => {e.preventDefault();await axios.post('http://localhost:8080/users/login', {email: email,password: password}).then((response) => {// TODO: todolist로 이동 (refresh)console.log(response)console.log(response.data.token)localStorage.setItem('isUser', response.data.token);modalOpen(response.data.message);}).catch((error) => {console.log(error)modalOpen(error.response.data.details);})}return (<UseAuthFormemail={email}setEmail={setEmail}password={password}setPassword={setPassword}modalIsOpen={modalIsOpen}setIsOpen={setIsOpen}onSubmit={onSubmit}modalText={modalText}setModalText={setModalText}isUser={true}/>)};