퍼블리싱 및 CSS

div를 감싸고 있는 input에 focus 효과주는법

벨보이 2024. 5. 13. 14:42

🤔 Input 안에 div 요소를 넣을 수 없어 focus를 활용한 border-color 변경이 어려워 졌다..

🧐  GPT에게 도움 받기

// React, Tailwind CSS, 그리고 TypeScript를 사용하여 Next.js 프로젝트에 맞게 <input> 필드의 포커스 상태에서 테두리 색상을 변경하는 방법을 설명하겠습니다.

// Tailwind CSS는 유틸리티 클래스를 통해 포커스 상태의 스타일을 쉽게 제어할 수 있습니다. focus: 접두사를 사용하여 포커스 상태일 때의 스타일을 정의할 수 있습니다. 아래 코드는 <input> 필드가 포커스될 때 테두리 색상을 변경하는 방법을 보여줍니다:

typescript
Copy code
import React from 'react';

interface SearchInputProps {
  placeholder?: string;
}

const SearchInput: React.FC<SearchInputProps> = ({ placeholder = "검색..." }) => {
  return (
    <div className="flex items-center border-2 border-gray-300 p-2 rounded-lg focus-within:border-blue-500">
      <input
        type="text"
        placeholder={placeholder}
        className="flex-1 p-2 outline-none border-gray-300 focus:border-blue-500"
      />
      <button className="text-gray-600 focus:outline-none">
        <i className="fas fa-search"></i>
      </button>
    </div>
  );
}

export default SearchInput;

 

😆  응용해서 적용해보기

 

focus-within:을 사용하면 추가로 작업없이 진행이 가능했다

 <div className={`flex items-center justify-between rounded-[4px] focus-within:border-black ${borderClasses} pl-3 py-[14px]`}>
        <input className="w-full text-[16px] font-sans text-gray_scale-800 " placeholder={placeholderText} type={type}  {...restProps}/>
        <div>

 

💪 출처 및 도움주신분들

GPT