label이용시 id 중복 해결

임혁진·2024년 2월 16일
0

로빌

목록 보기
14/15

위 input 컴포넌트는 label태그와 input 태그를 이용해 부드럽게 transition하는 박스 ui다. 그런데 이때 input태그와 labletag를 연결하기 위해 for(혹은 react에서 htmlFor)를 사용해 id로 바인딩하게 되는데 하나의 id를 사용할 경우 컴포넌트 재사용시 중복되기 때문에 제대로 1대1 바인딩이 되지 않는다.

따라서 고유한 id를 만들어서 해당 컴포넌트를 포커싱 할 수 있도록 해야한다.

uuid

uuid를 설치해 고유한 id를 만들고 1대1 바인딩할 수 있게 만들어 해결했다.

import React, { useState } from "react";
import { v4 as uuidv4 } from "uuid";

const InputBoxWithPlaceholder = ({ placeholder, type, onChange }) => {
  const [value, setValue] = useState("");

  const handleChange = (event) => {
    setValue(event.target.value);
    onChange(event.target.value);
  };

  const boxId = uuidv4();

  return (
    <div className="relative">
      <label
        className={`absolute left-4 transition-all ${value ? " top-2 text-xs" : " top-3 text-base"} text-gray-400`}
        htmlFor={boxId}
      >
        {placeholder}
      </label>
      <input
        id={boxId}
        type={type || "text"}
        value={value}
        onChange={handleChange}
        className={`box-border h-12 w-full rounded-2xl border-none bg-gray-200 pl-4 text-gray-700 transition-all focus:outline-none ${value ? "text-md pt-3" : "pt-0 text-base"}`}
      />
    </div>
  );
};

export default InputBoxWithPlaceholder;
profile
TIL과 알고리즘

0개의 댓글