bravo my life!

[Ionic-React] TypeScript, styled-components 로 조건 변경시 CSS 바꿔주기 본문

개발기/[Travelit] Ionic-React

[Ionic-React] TypeScript, styled-components 로 조건 변경시 CSS 바꿔주기

losajjang 2022. 7. 17. 21:56
728x90

1. 개요

boolean값으로 상태를 관리하며 어떤 아이콘을 false때는 상단에 빨간점을 표시하지 않고, true때는 상단에 빨간점을 표시하는 기능을 만들어 볼 것이다.

2. 코드 상세

//HomeHeader.tsx
import { useState } from 'react';
import styled from 'styled-components';

//인터페이스를 사용하여 NotiState의 타입을 지정해준다.
interface NotiState {
  noti: boolean;
}

const NotificationButtons = styled(IonButtons)`
  margin-right: 20px;
`;

//noti의 boolean 상태값에 따라 백그라운드 이미지를 바꾸어 줄 것이다. 
const NotificationButton = styled(IonButton)<NotiState>`
  background-image: ${({ noti }) =>
    (noti
      ? "url('/assets/icon/notification_notConfirm.png')"
      : "url('/assets/icon/notification_confirmed.png')")};
  background-size: 24px;
  background-repeat: no-repeat;
  background-position: center;
  width: 24px;
`;

const HomeHeader = () => {
  // 알림이 있다면 setNoti(true)로 알림 아이콘을 바꾸어 준다.
  const [noti, setNoti] = useState<boolean>(false);

  return (
    <IonHeader>
      <IonToolbar>
        <NotificationButtons slot="end">
          <NotificationButton
            fill="clear"
            noti={noti}
            routerLink="/noti"
          ></NotificationButton>
        </NotificationButtons>
      </IonToolbar>
    </IonHeader>
  );
};

export default HomeHeader;

코드의 결과물은 다음과 같다.

좌측은 noti의 상태가 false일 경우, 우측은 noti의 상태가 true일 경우이다.