[TIL] 내일배움캠프 React 과정 2024.06.24

김형빈·2024년 6월 24일
0

내일배움캠프

목록 보기
46/81

오늘의 한 일

  • 알고리즘 라이브 수업
  • 챌린지반 라이브 수업
    • 재사용성 높은 커스텀 컴포넌트 만들기
  • Favorite Countries (개인 과제)
    • type 설정
    • api 호출

tailwind를 활용한 재사용성 높은 컴포넌트

  • tailwind를 사용해서 재사용서어 높은 컴포넌트를 만들어보자

예시(Chips)

첫 번째 방법

  • 라이브러리 없이 변수에 따라 속성을 지정해주는 방법
function Chip({ label, intent }: ChipProps) {
  const colorClassName = intent === "primary" ? "bg-blue-500 border-blue-500 text-white" : intent === "warning" ? "bg-yellow-500 border-yellow-500 text-white": "";
  
  return <div className=`text-sm border rounded-full px-2.5 py-0.5 hover:opacity-50 transition-opacity ${colorClassName}`>{label}</div>;
}
  • 간단하지만 다른 옵션이 생긴다면??
  • 너무나도 복잡한 조건문을 사용해야 한다.

두 번째 방법

  • clsx(라이브러리)를 사용하여 속성을 지정한다.
function Chip({ label, intent }: ChipProps) {
  clsx({
  "bg-blue-500 border-blue-500 text-white": color === "blue",
  "bg-yellow-500 border-yellow-500 text-white": color === "yellow",
 });
  
  return <div className=`text-sm border rounded-full px-2.5 py-0.5 hover:opacity-50 transition-opacity ${colorClassName}`>{label}</div>;
}
  • 첫 번째 방법보다 옵션을 추가하는 게 직관적이게 되었지만 여전히 작성해야 되는 코드 양이 많다...

마지막 방법 (효과적인 방법)

  • cva(라이브러리)를 사용하여 속성을 지정한다.
function Chip({ label, intent }: ChipProps) {
  
const chipVariants = cva("text-sm border rounded-full px-2.5 py-0.5 hover:opacity-50 transition-opacity", {
  variants: {
    intent: {
      primary: "bg-blue-500 border-blue-500 text-white",
      secondary: "bg-gray-500 border-gray-500 text-white",
      danger: "bg-red-500 border-red-500 text-white",
      warning: "bg-yellow-500 border-yellow-500 text-white",
      info: "bg-violet-500 border-violet-500 text-white",
      default: "bg-white border-black text-black",
    },
  },
  defaultVariants: {
    intent: "default",
  },
});

  return <div className={chipVariants({ intent })}>{label}</div>;
}
  • 속성 값을 지정하고 이를 조합하여 사용합니다.

오늘의 회고

새로운 팀원들과 새로운 한 주가 시작되었다. 굉장히 활기찬 팀원분들과 팀을 이루게 되었다.. ㅎ 이번주도 열심히 해보자
profile
The secret of getting ahead is getting started.

0개의 댓글