Recent Posts
Recent Comments
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Today
Total
관리 메뉴

DH의 개발 공부로그

[React] 로그인 페이지 비밀번호 보기/숨기기 구현하기! - input type 변경 본문

React

[React] 로그인 페이지 비밀번호 보기/숨기기 구현하기! - input type 변경

DeveloperDH 2023. 5. 10. 15:15
728x90

비밀번호 보기/숨기기

로그인 페이지에서 이제는 필수가 되어버린 기능인 입력하는 비밀번호를 보거나 숨기는 기능을 아주 간단하게 구현을 해보았습니다.
리액트로 작업을 했기 때문에 약간의 차이만 있을 뿐 자바스크립트 코드를 기반으로 하기 때문에 자바스크립트 환경에서도 구현이 가능합니다.

코드 구현

마크업

아래의 코드를 이용하여 위의 이미지처럼 작업을 하였고, 스타일은 module을 이용하여 작업을 했습니다.
해당 스타일 코드는 지금 상황에서 중요한 부분이 아니기 때문에 생략하겠습니다.

function app () {
  const [userIdInput, setUserIdInput] = useState('')
  const [userPwInput, setUserPwInput] = useState('')
  const [isShowPwChecked, setShowPwChecked] = useState(false)
  const passwordRef = useRef(null)

  return (
    <div className={$.login_container}>
      <form>
        <div className={$.input_row}>
          <input type='text' name='userId' id='id' placeholder='아이디' 
                 value={userIdInput}
                 onChange={handleChangeInput}/>
          {
          userIdInput && <button>X</button>
          }
        </div>
        <div className={$.input_row}>
          <input type='password' name='userPw' id='password' placeholder='비밀번호'
                 maxLength={16}
                 value={userPwInput}
                 onChange={handleChangeInput}
                 ref={passwordRef}/>
          {
          userPwInput && <button>X</button>
          }
        </div>
        <div className={$.show_password_button}>
          <label>
            <input type='checkbox' onChange={handleShowPwChecked} />
            <span className={$.show_password_title}>비밀번호 보기</span>
          </label>
        </div>
        <div className={$.login_button}>로그인</div>
        <div className={$.join_button}>
          <div>회원가입</div>
        </div>
      </form>
    </div>
  )
}

기능 구현

이제 본격적으로 보기/숨기기 기능이 가능하게끔 하는 코드를 확인해 보겠습니다.

<input type='password' name='userPw' id='password' placeholder='비밀번호'
       maxLength={16}
       value={userPwInput}
       onChange={handleChangeInput}
       ref={passwordRef}/>

우선 비밀번호 inputtypepassword로 설정하였습니다.
비밀번호 보기 체크박스가 체크가 되면 비밀번호 인풋의 typetext로 바꿔주기만 하면 되는 아주 간단한 방식입니다.
그 방식을 구현한 함수 코드를 확인해 보겠습니다.

const [isShowPwChecked, setShowPwChecked] = useState(false)
const passwordRef = useRef(null)

const handleShowPwChecked = async () => {
  const password = await passwordRef.current
  if (password === null) return

  await setShowPwChecked(!isShowPwChecked)
  if(!isShowPwChecked) {
    password.type = 'text';
  } else {
    password.type = 'password';
  }
}

handleShowPwChecked 함수에서는 우선 동기적으로 함수가 실행이 되게 async & await을 이용을 하였습니다.
그런 상태에서 useRef로 비밀번호 인풋창을 제어할 수 있도록 해주고 조건문을 통해서 비밀번호 인풋창의 type을 바꿔주기만 하면 기능이 구현이 됩니다.

728x90
Comments