ppotatoG


Back to all posts

React useForm custom

Written by ppotatoG & Posted on October 26th, 2022

로그인 페이지 & 회원가입 페이지 내 동일 폼 재사용을 위한 컴포넌트

  1. input value handling
  2. input 하단으로 error message 노출
  3. isUser 사용으로 로그인 버튼 노출
// common/UseAuthForm.tsx
export 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 handling
const 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>
<input
type="email"
name="email"
id="email"
required
value={email}
onChange={onChangeEmailCheck}
/>
</div>
// error message
{emailErrorMessage !== '' && <p className={styles.errorMessage}>{emailErrorMessage}</p>}
<div className={styles.auth__item}>
<label htmlFor='password'>비밀번호</label>
<input
type="password"
name="password"
id="password"
required
value={password}
onChange={onChangePasswordCheck}
/>
</div>
// error message
{passwordErrorMessage && <p className={styles.errorMessage}>{passwordErrorMessage}</p>}
<div className={styles.btn_wrap}>
// 회원가입 페이지에서 로그인 버튼 미노출
{
isUser &&
<button
disabled={!emailError || !passwordError}
className={styles.btn_wrap__item}>
로그인
</button>
}
<a className={styles.btn_wrap__item} href="../auth/SignUp">회원가입</a>
</div>
{
modalIsOpen &&
<CustomModal
text={modalText}
modalIsOpen={modalIsOpen}
setIsOpen={setIsOpen}
/>
}
</form>
)
};
// SignUp.tsx
const 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 (
<UseAuthForm
email={email}
setEmail={setEmail}
password={password}
setPassword={setPassword}
modalIsOpen={modalIsOpen}
setIsOpen={setIsOpen}
onSubmit={onSubmit}
modalText={modalText}
setModalText={setModalText}
isUser={false}
/>
)
};
// SignIn.tsx
const 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 (
<UseAuthForm
email={email}
setEmail={setEmail}
password={password}
setPassword={setPassword}
modalIsOpen={modalIsOpen}
setIsOpen={setIsOpen}
onSubmit={onSubmit}
modalText={modalText}
setModalText={setModalText}
isUser={true}
/>
)
};

common/UseAuthForm.tsx

auth/SignIn.tsx

auth/SignUp.tsx


Posted on October 26th, 2022