React

Show

TypeScript
TypeScript
React
React
조건부 렌더링을 선언적으로 처리하는 컴포넌트입니다.
when
으로 조건을 전달하고, 조건을 만족하지 않으면
fallback
을 렌더링합니다. 제네릭 타입을 통해 자식 요소의 타입을 추론할 수 있습니다.

구현

import type { ReactNode } from 'react';

// boolean
export function Show(props: {
  when: boolean;
  children: ReactNode | (() => ReactNode);
  fallback?: ReactNode | (() => ReactNode);
}): ReactNode;

// truthy
export function Show<T>(props: {
  when: T | null | undefined | false | 0 | '';
  children: ReactNode | ((value: NonNullable<T>) => ReactNode);
  fallback?: ReactNode | (() => ReactNode);
}): ReactNode;

// boolean | truthy
export function Show<T>({
  children,
  when,
  fallback = null,
}: {
  when: T | boolean | null | undefined;
  children: ReactNode | ((value: NonNullable<T>) => ReactNode);
  fallback?: ReactNode | (() => ReactNode);
}): ReactNode {
  // truthy 체크
  const isTruthy = Boolean(when);

  // falsy면 fallback 렌더링
  if (!isTruthy) {
    return typeof fallback === 'function' ? fallback() : fallback;
  }

  // truthy면 children 렌더링
  if (typeof children === 'function') {
    return children(when as NonNullable<T>);
  }

  return <>{children}</>;
}

사용법

1.
boolean
조건

const fruit = 'apple';

// 결과: 사과
<Show when={fruit === 'apple'}>
  <span>사과</span>
</Show>;

2. 타입 추론

const fruit: string | null = 'apple'

// 결과: apple
// typeof result === 'string'
<Show when={fruit} >
	{ result => <span>{result}</span>}
</Show>

3.
fallback
렌더링

const fruit = 'apple'

// 결과: 과일이 없어요
<Show when={false} fallback={<span>과일이 없어요</span>}>
	<span>{fruit}</span>
</Show>

참조