[React]-조건에 따라 className 추가하기!(ft.TailwindCSS)

badassong·2023년 5월 15일
0

React

목록 보기
43/56
post-thumbnail

유튜브 상세페이지에 description 부분에서
description이 초기에는 세 줄로만 보이고 토글 시 펼쳐졌다 줄어들었다 하는 기능을 구현하고 싶었다.

Tailwind를 사용하고 있어서 class name이 여러 개 지정되어 있는데
이 상태에서 삼항연산자를 사용해서 class name이 toggle 되게 할 수 없을까? 고민하면서 구글링을 하다가 해결책 발견!

  const [isLong, setIsLong] = useState(false);
  const onClickLong = () => {
    setIsLong((isLong) => !isLong);
  };

먼저 useState로 상태 토글 기능을 만들어주고!

 <p className=
 {"description whitespace-pre-wrap text-sm" + (isLong ? " long" : "")}
    onClick={onClickLong}>
    {video.items[0].snippet.description}
 </p>

이렇게 삼항연산자로 class name을 토글할 수 있다!!

🚨 추가할 class name 입력할 때 꼭 한 칸 띄우고 입력해야 함!!(" long") 안 그럼 text-smlong 이렇게 보인다!!

profile
프론트엔드 대장이 되어보쟈

0개의 댓글