상세 컨텐츠

본문 제목

[floating Label] 움직이는 placeholder 만들기

본문

처음 디자인을 받고 placeholder가 움직이고... 비키는게 현실적으로 가능한가?
했는데 불가능은 없다 🤣

 

이 비현실적인 UI의 진실은 placeholder가 placeholder가 아니라는 것에 있다 😉

내가 작성한 코드를 자세히 보면 움직여야할 placeholder가 안보인다.CSS와 React의 useState를 활용하여 상태에 따라 라벨 위치를 변경하는 방식으로 구현을 진행했기 때문이다. 

👩🏻‍💻구현 코드 

          <InputContainer>
            <FloatingLabel className={isFocused || employeeId ? "active" : ""}>아이디를 입력하세요</FloatingLabel>
            <Input
              type="text"
              value={employeeId}
              onChange={(e) => setEmployeeId(e.target.value)}
              onFocus={() => setIsFocused(true)}
              onBlur={() => setIsFocused(!!employeeId)}
              required
            />
          </InputContainer>

          <InputContainer>
            <FloatingLabel className={isPasswordFocused || password ? "active" : ""}>비밀번호를 입력하세요</FloatingLabel>
            <Input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              onFocus={() => setIsPasswordFocused(true)}
              onBlur={() => setIsPasswordFocused(!!password)}
              required
            />
          </InputContainer>
  • 사용자가 입력을 위해 Input을 눌렀을 때 : FloatingLabel 위에 있음
  • 사용자가 입력할 때 : FloatingLabel 위에 있음
  • 사용자가 아무것도 안할 때 : FloatingLabel이 Input 가운데 떠있음
         ➡️ 사용자가 패스워드를 치는지 onFocus*, onBlur** 의 상태를 확인할 수 있음

*onFocus 
 : 클릭 되었을 때
**onBlur
 : 클릭이 해제되었을 때

👩🏻‍💻함께 사용한 styled-component 코드

const FloatingLabel = styled.span`
  position: absolute;
  left: 14px;
  top: 45%;
  transform: translateY(-50%);
  font-size: 16px;
  color: var(--gray-600, #A6A5A5);
  transition: all 0.2s ease-in-out;
  pointer-events: none;

  &.active {
    top: 10px;
    font-size: 12px;
    color: var(--gray-500, #C0C0C0);
  }
`;

const Input = styled.input`
  width: 100%;
  height: 44px;
  padding: 10px 12px;
  border-radius: 8px;
  border: 2px solid var(--gray-600, #A6A5A5);
  font-size: 14px;
  background: transparent;
  transition: all 0.2s ease-in-out;
  max-width: 320px;

  &:focus {
    border: 2px solid var(--primary-main-200, #009857);
    outline: none;
  }
`;

 

관련글 더보기