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 | 타입 | 필수 | 기본값 | 설명 |
|---|---|---|---|---|
value | string | number | 예 | - | 매칭할 값 |
caseBy | Partial<Record<Case, JSX.Element | null>> | 예 | - | 값과 컴포넌트의 매핑 객체 |
defaultComponent | JSX.Element | null | 아니오 | null | 매칭되는 케이스가 없을 때 렌더링할 컴포넌트 |
동작 방식
value가null또는undefined이면defaultComponent반환value가caseBy에 존재하면 해당 컴포넌트 반환caseBy[value]가undefined이면defaultComponent반환- 매칭되는 케이스가 없으면
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는 복잡한 조건부 렌더링을 선언적으로 표현할 수 있어 코드 가독성을 높입니다.