Skip to content

SwitchCase

값에 따라 다른 컴포넌트를 렌더링하는 선언적 조건부 렌더링 컴포넌트입니다.

Import

ts
import { SwitchCase } from '@liner-engineering/orbit-core';

사용법

기본 사용법

tsx
<SwitchCase
  value={status}
  caseBy={{
    active: <span style={{ color: 'green' }}>활성</span>,
    inactive: <span style={{ color: 'gray' }}>비활성</span>,
    pending: <span style={{ color: 'orange' }}>대기중</span>,
  }}
/>

기본값 사용

tsx
<SwitchCase
  value={status}
  caseBy={{
    success: <SuccessIcon />,
    error: <ErrorIcon />,
  }}
  defaultComponent={<UnknownIcon />}
/>

숫자 값 사용

tsx
<SwitchCase
  value={step}
  caseBy={{
    1: <Step1 />,
    2: <Step2 />,
    3: <Step3 />,
  }}
/>

API

tsx
interface Props<Case extends string | number> {
  value: Case;
  caseBy: Partial<Record<Case, JSX.Element | null>>;
  defaultComponent?: JSX.Element | null;
}

function SwitchCase<Case extends string | number>(props: Props<Case>): JSX.Element | null;

Props

Prop타입필수기본값설명
valuestring | number-매칭할 값
caseByPartial<Record<Case, JSX.Element | null>>-값과 컴포넌트의 매핑 객체
defaultComponentJSX.Element | null아니오null매칭되는 케이스가 없을 때 렌더링할 컴포넌트

동작 방식

  1. valuenull 또는 undefined이면 defaultComponent 반환
  2. valuecaseBy에 존재하면 해당 컴포넌트 반환
  3. caseBy[value]undefined이면 defaultComponent 반환
  4. 매칭되는 케이스가 없으면 defaultComponent 반환

예시

tsx
type Status = 'loading' | 'success' | 'error';

function StatusBadge({ status }: { status: Status }) {
  return (
    <SwitchCase
      value={status}
      caseBy={{
        loading: <Spinner />,
        success: <CheckIcon />,
        error: <ErrorIcon />,
      }}
    />
  );
}

if-else 대신 사용

SwitchCase는 복잡한 조건부 렌더링을 선언적으로 표현할 수 있어 코드 가독성을 높입니다.

Released under the MIT License.