React) 핸드폰 번호 입력시 자동 대시(-)기호 삽입 및 삭제

김명성·2022년 10월 21일
0
post-custom-banner

  /** 데시기호(-)일 때 backspace를 누르면 바로 뒤 숫자까지 삭제시켜주는 함수 */

  const deleteDashHandler = useCallback((e) => {
    
    if(e.which === 8 && applyCounselForm.phoneNumber.charAt(applyCounselForm.phoneNumber.length -1) === '-'){
      e.preventDefault();
      setApplyCounselForm(prev => ({
        ...prev,
        phoneNumber: prev.phoneNumber.slice(0,prev.phoneNumber.length -2)
      }))
      return;
    };
  },[applyCounselForm.phoneNumber, setApplyCounselForm])
  
  useEffect(() => {
    
    if(applyCounselForm.phoneNumber.length === 3 && applyCounselForm.phoneNumber.charAt(applyCounselForm.phoneNumber.length -1) !== '-'){
      setApplyCounselForm(prev => ({
        ...prev,
        phoneNumber: prev.phoneNumber += '-'
      }))
    }else if(applyCounselForm.phoneNumber.length === 8 && applyCounselForm.phoneNumber.charAt(applyCounselForm.phoneNumber.length -1) !== '-') {
      setApplyCounselForm(prev => ({
        ...prev,
        phoneNumber: prev.phoneNumber += '-'
      }))
    }
  },[applyCounselForm.phoneNumber, setApplyCounselForm])

...
// onChange와 onKeyDown을 둘다 사용.
<PhoneInput  name="phoneNumber" value={applyCounselForm.phoneNumber || ''} onChange={applyCounselFormHandler} onKeyDown={deleteDashHandler}  type="tel" inputMode="numeric"/>
...
post-custom-banner

0개의 댓글