Last active
March 29, 2022 10:11
-
-
Save ding-co/fb12e770fa99037f4c52bbf1ba6e7a98 to your computer and use it in GitHub Desktop.
form-hooks.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// form-hooks.ts | |
import React, { useCallback, useState } from 'react'; | |
export interface IuseInputProps { | |
type: string; | |
defValue: string | number; | |
} | |
const useInput = ({ type, defValue }: IuseInputProps) => { | |
const [value, setValue] = useState(defValue); | |
return { | |
inputProps: { | |
type, | |
value, | |
onChange: useCallback((event: React.FormEvent<HTMLInputElement>) => { | |
setValue(event.currentTarget.value); | |
}, []), | |
}, | |
resetFn: () => { | |
setValue(defValue); | |
}, | |
}; | |
}; | |
export { useInput }; | |
// HooksTest.tsx | |
import { FormEvent } from 'react'; | |
import { useInput } from './form-hooks'; | |
const HooksTest = () => { | |
const { inputProps: idInput, resetFn: resetIdInput } = useInput({ | |
type: 'text', | |
defValue: '', | |
}); | |
const { inputProps: passwordInput, resetFn: resetPasswordInput } = useInput({ | |
type: 'password', | |
defValue: '', | |
}); | |
const { | |
inputProps: passwordConfirmInput, | |
resetFn: resetPasswordConfirmInput, | |
} = useInput({ | |
type: 'password', | |
defValue: '', | |
}); | |
const { inputProps: emailInput, resetFn: resetEmailInput } = useInput({ | |
type: 'email', | |
defValue: '', | |
}); | |
const { inputProps: telInput, resetFn: resetTelInput } = useInput({ | |
type: 'tel', | |
defValue: '', | |
}); | |
const onSubmit = (event: FormEvent<HTMLFormElement>) => { | |
event.preventDefault(); | |
resetIdInput(); | |
resetPasswordInput(); | |
resetPasswordConfirmInput(); | |
resetEmailInput(); | |
resetTelInput(); | |
}; | |
return ( | |
<form | |
onSubmit={onSubmit} | |
style={{ | |
width: '100%', | |
height: '100%', | |
display: 'flex', | |
flexDirection: 'column', | |
justifyContent: 'center', | |
alignItems: 'center', | |
}} | |
> | |
<label> | |
<span>ID </span> | |
<input {...idInput} autoFocus required /> | |
</label> | |
<br /> | |
<label> | |
<span>비밀번호 </span> | |
<input {...passwordInput} required /> | |
</label> | |
<br /> | |
<label> | |
<span>비밀번호 확인</span> | |
<input {...passwordConfirmInput} required /> | |
</label> | |
<br /> | |
<label> | |
<span>이메일 </span> | |
<input {...emailInput} required /> | |
</label> | |
<br /> | |
<label> | |
<span>전화번호 </span> | |
<input {...telInput} required /> | |
</label> | |
<br /> | |
<button>저장</button> | |
</form> | |
); | |
}; | |
export default HooksTest; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment