Alert

Alert (알림)

Alert는 사용자에게 경고 메시지를 표시할 때 사용하는 컴포넌트예요. 사용자 동작으로 닫을 수 있는 지속적 정적 컨테이너를 만들 때도 쓰이죠.

출처: 문서

본문

언제 사용하나요

  • 사용자에게 알림 메시지를 보여줘야 할 때.
  • 사용자 동작으로 닫을 수 있는 지속적인 정적 컨테이너가 필요할 때.

예제 (Examples)

기본 (Basic)

짧은 메시지에 쓰는 가장 단순한 사용법이에요.

import React from 'react';
import { Alert } from 'antd';

const App: React.FC = () => <Alert title="Success Text" type="success" />;

export default App;

더 많은 타입 (More types)

Alert에는 4가지 타입이 있어요: success, info, warning, error.

import React from 'react';
import { Alert } from 'antd';

const App: React.FC = () => (
  <>
    <Alert title="Success Text" type="success" />
    <br />
    <Alert title="Info Text" type="info" />
    <br />
    <Alert title="Warning Text" type="warning" />
    <br />
    <Alert title="Error Text" type="error" />
  </>
);

export default App;

채움 (Filled)

variant="filled"로 테두리를 숨겨요.

import React from 'react';
import { Alert } from 'antd';

const App: React.FC = () => <Alert title="Info Text" type="info" variant="filled" />;

export default App;

닫기 가능 (Closable)

닫기 버튼을 표시해요.

import React from 'react';
import { Alert } from 'antd';

const onClose: React.MouseEventHandler<HTMLButtonElement> = (e) => {
  console.log(e, 'I was closed.');
};

const App: React.FC = () => (
  <>
    <Alert
      title="Warning Title"
      type="warning"
      closable={{ closeIcon: true, onClose, 'aria-label': 'close' }}
    />
    <br />
    <Alert
      title="Success Title"
      type="success"
      closable={{ closeIcon: true, onClose, 'aria-label': 'close' }}
    />
    <br />
    <Alert
      title="Info Title"
      type="info"
      closable={{ closeIcon: true, onClose, 'aria-label': 'close' }}
    />
    <br />
    <Alert
      title="Error Title"
      type="error"
      closable={{ closeIcon: true, onClose, 'aria-label': 'close' }}
    />
  </>
);

export default App;

설명 (Description)

알림 메시지에 대한 추가 설명이에요.

import React from 'react';
import { Alert } from 'antd';

const App: React.FC = () => (
  <>
    <Alert
      title="Success Text"
      description="Success Description Success Description Success Description"
      type="success"
    />
    <br />
    <Alert
      title="Info Text"
      description="Info Description Info Description Info Description Info Description"
      type="info"
    />
    <br />
    <Alert
      title="Warning Text"
      description="Warning Description Warning Description Warning Description Warning Description"
      type="warning"
    />
    <br />
    <Alert
      title="Error Text"
      description="Error Description Error Description Error Description Error Description"
      type="error"
    />
  </>
);

export default App;

아이콘 (Icon)

관련 아이콘은 정보를 더 명확하고 친근하게 만들어 줘요.

import React from 'react';
import { Alert } from 'antd';

const App: React.FC = () => (
  <>
    <Alert title="Success Tips" type="success" showIcon />
    <br />
    <Alert title="Informational Notes" type="info" showIcon />
    <br />
    <Alert title="Warning" type="warning" showIcon closable />
    <br />
    <Alert title="Error" type="error" showIcon />
    <br />
    <Alert
      title="Success Tips"
      description="Detailed description and advice about successful copywriting."
      type="success"
      showIcon
    />
    <br />
    <Alert
      title="Informational Notes"
      description="Additional description and information about copywriting."
      type="info"
      showIcon
    />
    <br />
    <Alert
      title="Warning"
      description="This is a warning notice about copywriting."
      type="warning"
      showIcon
      closable
    />
    <br />
    <Alert
      title="Error"
      description="This is an error message about copywriting."
      type="error"
      showIcon
    />
  </>
);

export default App;

배너 (Banner)

Alert를 페이지 상단의 배너로 표시해요.

import React from 'react';
import { Alert } from 'antd';

const App: React.FC = () => (
  <>
    <Alert title="Warning text" banner />
    <br />
    <Alert
      title="Very long warning text warning text text text text text text text"
      banner
      closable
    />
    <br />
    <Alert showIcon={false} title="Warning text without icon" banner />
    <br />
    <Alert type="error" title="Error text" banner />
  </>
);

export default App;

순환 배너 (Loop Banner)

react-text-loop-next나 react-fast-marquee와 함께 사용해 순환 배너를 보여줘요.

import React from 'react';
import { Alert } from 'antd';
import Marquee from 'react-fast-marquee';

const App: React.FC = () => (
  <Alert
    banner
    title={
      <Marquee pauseOnHover gradient={false}>
        I can be a React component, multiple React components, or just some text.
      </Marquee>
    }
  />
);

export default App;

부드럽게 언마운트 (Smoothly Unmount)

닫을 때 Alert를 부드럽게 언마운트해요.

import React, { useState } from 'react';
import { Alert, Switch } from 'antd';

const App: React.FC = () => {
  const [visible, setVisible] = useState(true);

  const handleClose = () => {
    setVisible(false);
  };

  return (
    <>
      {visible && (
        <Alert
          title="Alert Message Text"
          type="success"
          closable={{ closeIcon: true, afterClose: handleClose }}
        />
      )}
      <p>click the close button to see the effect</p>
      <Switch
        aria-label="Alert visibility"
        onChange={setVisible}
        checked={visible}
        disabled={visible}
      />
    </>
  );
};

export default App;

ErrorBoundary

React에서 오류 처리를 더 쉽게 해 주는 ErrorBoundary 컴포넌트예요.

import React, { useState } from 'react';
import { Alert, Button } from 'antd';

const { ErrorBoundary } = Alert;

const ThrowError: React.FC = () => {
  const [error, setError] = useState<Error>();
  const onClick = () => {
    setError(new Error('An Uncaught Error'));
  };

  if (error) {
    throw error;
  }
  return (
    <Button danger onClick={onClick}>
      Click to throw an error
    </Button>
  );
};

const App: React.FC = () => (
  <ErrorBoundary>
    <ThrowError />
  </ErrorBoundary>
);

export default App;

커스텀 액션 (Custom action)

커스텀 액션이에요.

import React from 'react';
import { Alert, Button, Flex } from 'antd';

const App: React.FC = () => (
  <>
    <Alert
      title="Success Tips"
      type="success"
      showIcon
      action={
        <Button size="small" type="text">
          UNDO
        </Button>
      }
      closable
    />
    <br />
    <Alert
      title="Error Text"
      showIcon
      description="Error Description Error Description Error Description Error Description"
      type="error"
      action={
        <Button size="small" danger>
          Detail
        </Button>
      }
    />
    <br />
    <Alert
      title="Warning Text"
      type="warning"
      action={
        <Button type="text" size="small">
          Done
        </Button>
      }
      closable
    />
    <br />
    <Alert
      title="Info Text"
      description="Info Description Info Description Info Description Info Description"
      type="info"
      action={
        <Flex vertical gap="small" style={{ minWidth: 80 }}>
          <Button size="small" type="primary" block>
            Accept
          </Button>
          <Button size="small" danger ghost block>
            Decline
          </Button>
        </Flex>
      }
      closable
    />
  </>
);

export default App;

커스텀 제목 정렬 (Custom title alignment)

description이 설정되지 않았을 때, Alert는 아이콘·콘텐츠·액션·닫기 버튼을 하나의 그룹으로 세로 중앙 정렬해요. Ant Design은 토큰 파생 오프셋으로 이 기본 레이아웃을 flex-start로 바꾸지 않아요. 커스터마이즈된 styles가 폰트 크기·줄 높이·액션 크기를 바꿀 수 있어서, 그 오프셋이 실제 렌더링된 스타일과 더 이상 맞지 않게 되거든요. 줄바꿈하는 제목이 이 요소들을 첫 줄과 정렬해야 한다면, 시맨틱 styles로 조정하세요.

import React from 'react';
import { Alert, Button, Flex } from 'antd';
import type { AlertProps } from 'antd';

const wrapperStyle: React.CSSProperties = {
  width: 360,
};

const title = 'Long alert title wraps to multiple lines when the alert container is narrow enough.';

const titleLineHeight = 22;
const iconSize = 14;
const closeIconSize = 12;
const smallButtonHeight = 24;

const firstLineStyles: AlertProps['styles'] = {
  root: {
    alignItems: 'flex-start',
  },
  icon: {
    marginBlockStart: (titleLineHeight - iconSize) / 2,
  },
  actions: {
    marginBlockStart: (titleLineHeight - smallButtonHeight) / 2,
  },
  close: {
    marginBlockStart: (titleLineHeight - closeIconSize) / 2,
  },
};

const App: React.FC = () => (
  <Flex vertical gap="middle" style={wrapperStyle}>
    <Alert title={title} type="info" showIcon closable styles={firstLineStyles} />
    <Alert
      title={title}
      type="success"
      showIcon
      closable
      styles={firstLineStyles}
      action={
        <Button size="small" type="text">
          Action
        </Button>
      }
    />
  </Flex>
);

export default App;

커스텀 시맨틱 DOM 스타일링

classNames와 styles에 객체/함수를 전달해 Alert의 시맨틱 DOM 스타일을 커스터마이즈할 수 있어요.

import React from 'react';
import { Alert, Button, Flex } from 'antd';
import type { AlertProps, GetProp } from 'antd';
import { createStaticStyles } from 'antd-style';

const classNames = createStaticStyles(({ css }) => ({
  root: css`
    border: 2px dashed #ccc;
    border-radius: 8px;
    padding: 12px;
  `,
}));

const styleFn: AlertProps['styles'] = ({
  props: { type },
}): GetProp<AlertProps, 'styles', 'Return'> => {
  if (type === 'success') {
    return {
      root: {
        backgroundColor: 'rgba(82, 196, 26, 0.1)',
        borderColor: '#b7eb8f',
      },
      icon: {
        color: '#52c41a',
      },
    };
  }

  if (type === 'warning') {
    return {
      root: {
        backgroundColor: 'rgba(250, 173, 20, 0.1)',
        borderColor: '#ffe58f',
      },
      icon: {
        color: '#faad14',
      },
    };
  }

  return {};
};

const App: React.FC = () => {
  const alertSharedProps: AlertProps = {
    showIcon: true,
    classNames: {
      root: classNames.root,
    },
  };

  return (
    <Flex vertical gap="medium">
      <Alert
        {...alertSharedProps}
        title="Object styles"
        type="info"
        styles={{
          icon: {
            fontSize: 18,
          },
          section: {
            fontWeight: 500,
          },
        }}
        action={<Button size="small">Action</Button>}
      />
      <Alert {...alertSharedProps} title="Function styles" type="success" styles={styleFn} />
    </Flex>
  );
};

export default App;

API

공통 props 참고: Common props

속성 설명 타입 기본값 버전 전역 설정
action Alert의 액션 ReactNode - ×
afterClose 닫기 애니메이션이 끝났을 때 호출. closable.afterClose를 사용하세요 () => void - ×
banner 배너로 표시할지 여부 boolean false ×
variant Alert 스타일의 변형 outlined | filled outlined 6.4.0 6.4.0
classNames 컴포넌트 내부 각 시맨틱 구조의 클래스 커스터마이즈. 객체 또는 함수 지원 Record<SemanticDOM, string> | (info: { props }) => Record<SemanticDOM, string> - 6.0.0
closable 닫기 가능 설정 boolean | ClosableType & React.AriaAttributes false closable.closeIcon, closable.aria-*: 5.15.0
closeIcon (전역 설정만 지원) 커스텀 닫기 아이콘 ReactNode - × 5.14.0
description Alert의 추가 콘텐츠 ReactNode - ×
errorIcon (전역 설정만 지원) Alert 아이콘의 커스텀 오류 아이콘 ReactNode - × 6.2.0
icon 커스텀 아이콘, showIcon이 true일 때 유효 ReactNode - ×
infoIcon (전역 설정만 지원) Alert 아이콘의 커스텀 정보 아이콘 ReactNode - × 6.2.0
message Alert의 콘텐츠, title을 사용하세요 ReactNode - ×
onClose Alert가 닫힐 때 콜백, closable.onClose를 사용하세요 (e: MouseEvent) => void - ×
closeIcon 커스텀 닫기 아이콘, closable.closeIcon을 사용하세요 ReactNode - - ×
closeText 표시할 닫기 텍스트, closable.closeIcon을 사용하세요 ReactNode - - ×
showIcon 아이콘 표시 여부 boolean false, banner 모드에서는 기본값 true ×
styles 컴포넌트 내부 각 시맨틱 구조의 인라인 스타일 커스터마이즈. 객체 또는 함수 지원 Record<SemanticDOM, CSSProperties> | (info: { props }) => Record<SemanticDOM, CSSProperties> - 6.0.0
successIcon (전역 설정만 지원) Alert 아이콘의 커스텀 성공 아이콘 ReactNode - × 6.2.0
title Alert의 콘텐츠 ReactNode - ×
type Alert 스타일의 종류, 옵션: success, info, warning, error string info, banner 모드에서는 기본값 warning ×
warningIcon (전역 설정만 지원) Alert 아이콘의 커스텀 경고 아이콘 ReactNode - × 6.2.0

ClosableType

속성 설명 타입 기본값 버전
afterClose 닫기 애니메이션이 끝났을 때 호출 function - -
closeIcon 커스텀 닫기 아이콘 ReactNode - -
onClose Alert가 닫힐 때 콜백 (e: MouseEvent) => void - -

Alert.ErrorBoundary

속성 설명 타입 기본값 버전
description 표시할 커스텀 오류 설명 ReactNode {{ error stack }}
message 표시할 커스텀 오류 메시지, title을 사용하세요 ReactNode {{ error }}
title 표시할 커스텀 오류 제목 ReactNode {{ error }}

시맨틱 DOM (Semantic DOM)

https://ant.design/components/alert/semantic.md

디자인 토큰 (Design Token)

컴포넌트 토큰 (Alert)

토큰 이름 설명 타입 기본값
borderRadius Alert의 테두리 반지름 BorderRadius<string | number> | undefined 8
defaultPadding 기본 패딩 Padding<string | number> | undefined 8px 12px
withDescriptionIconSize 설명이 있을 때의 아이콘 크기 string | number 24
withDescriptionPadding 설명이 있을 때의 패딩 Padding<string | number> | undefined 20px 24px

전역 토큰 (Global Token)

토큰 이름 설명 타입 기본값
colorError 작업 실패의 시각 요소를 나타내는 데 사용. 예: 오류 Button, 오류 Result 컴포넌트 등 string
colorErrorBg 오류 상태의 배경색. string
colorErrorBorder 오류 상태의 테두리색. string
colorIcon 약한 액션. 예: allowClear 또는 Alert 닫기 버튼 string
colorIconHover 약한 액션 호버 색. 예: allowClear 또는 Alert 닫기 버튼 string
colorInfo 정보 토큰 시퀀스. Alert, Tag, Progress 등 컴포넌트가 이 map 토큰을 사용 string
colorInfoBg 정보 색의 밝은 배경색. string
colorInfoBorder 정보 색의 테두리색. string
colorPrimaryBorder 기본 색 그라데이션 아래의 스트로크 색. Slider 같은 컴포넌트의 스트로크에 사용 string
colorSuccess 작업 성공의 토큰 시퀀스. Result, Progress 등 컴포넌트가 이 map 토큰을 사용 string
colorSuccessBg 성공 색의 밝은 배경색, Tag와 Alert 성공 상태 배경색에 사용 string
colorSuccessBorder 성공 색의 테두리색, Tag와 Alert 성공 상태 테두리색에 사용 string
colorText W3C 표준을 준수하는 기본 텍스트 색. 가장 어두운 중성색이기도 함. string
colorTextHeading 제목의 폰트 색 제어. string
colorWarning 경고 map 토큰. Notification, Alert 등이 사용. Alert 또는 콘트롤 컴포넌트(Input)도 사용 string
colorWarningBg 경고 상태의 배경색. string
colorWarningBorder 경고 상태의 테두리색. string
fontFamily 시스템 기본 인터페이스 폰트와 화면 표시에 적합한 대체 폰트 라이브러리 세트 제공 string
fontSize 디자인 시스템에서 가장 널리 사용되는 폰트 크기. number
fontSizeIcon Select, Cascader 등의 동작 아이콘 폰트 크기 제어. 보통 fontSizeSM과 같음. number
fontSizeLG 큰 폰트 크기 number
lineHeight 텍스트의 줄 높이. number
lineType 기본 컴포넌트의 테두리 스타일 string
lineWidth 기본 컴포넌트의 테두리 너비 number
lineWidthFocus 컴포넌트가 포커스 상태일 때 선 너비 제어. number
marginSM 요소의 여백 제어, 중간-작은 크기. number
marginXS 요소의 여백 제어, 작은 크기. number
motionDurationMid 모션 속도, 중간 속도. 중간 요소 애니메이션 상호작용에 사용. string
motionDurationSlow 모션 속도, 느린 속도. 대형 요소 애니메이션 상호작용에 사용. string
motionEaseInOutCirc 프리셋 모션 곡선. string

더 알아보기 (Learn more)