Alert
Shoelace의 Alert 컴포넌트(sl-alert)는 중요한 메시지를 페이지 안(inline) 또는 토스트(toast) 알림 형태로 표시할 때 사용해요. 인라인 알림처럼 내용을 강조하거나, 토스트처럼 화면 모서리에 잠깐 떴다가 사라지는 알림으로 만들 수 있답니다.
출처: 문서
본문
Alert는 중요한 메시지를 인라인(inline)으로 표시하거나 토스트 알림(toast notification)으로 표시하는 데 사용해요.
<sl-alert open>
<sl-icon slot="icon" name="info-circle"></sl-icon>
This is a standard alert. You can customize its content and even the icon.
</sl-alert>
import SlAlert from '@shoelace-style/shoelace/dist/react/alert';
import SlIcon from '@shoelace-style/shoelace/dist/react/icon';
const App = () => (
<SlAlert open>
<SlIcon slot="icon" name="info-circle" />
This is a standard alert. You can customize its content and even the icon.
</SlAlert>
);
open 속성(attribute)이 없으면 Alert가 화면에 보이지 않아요.
Examples
Variants
variant 속성(attribute)을 설정하면 Alert의 변형(variant)을 바꿀 수 있어요.
<sl-alert variant="primary" open>
<sl-icon slot="icon" name="info-circle"></sl-icon>
<strong>This is super informative</strong><br />
You can tell by how pretty the alert is.
</sl-alert>
<br />
<sl-alert variant="success" open>
<sl-icon slot="icon" name="check2-circle"></sl-icon>
<strong>Your changes have been saved</strong><br />
You can safely exit the app now.
</sl-alert>
<br />
<sl-alert variant="neutral" open>
<sl-icon slot="icon" name="gear"></sl-icon>
<strong>Your settings have been updated</strong><br />
Settings will take effect on next login.
</sl-alert>
<br />
<sl-alert variant="warning" open>
<sl-icon slot="icon" name="exclamation-triangle"></sl-icon>
<strong>Your session has ended</strong><br />
Please login again to continue.
</sl-alert>
<br />
<sl-alert variant="danger" open>
<sl-icon slot="icon" name="exclamation-octagon"></sl-icon>
<strong>Your account has been deleted</strong><br />
We're very sorry to see you go!
</sl-alert>
import SlAlert from '@shoelace-style/shoelace/dist/react/alert';
import SlIcon from '@shoelace-style/shoelace/dist/react/icon';
const App = () => (
<>
<SlAlert variant="primary" open>
<SlIcon slot="icon" name="info-circle" />
<strong>This is super informative</strong>
<br />
You can tell by how pretty the alert is.
</SlAlert>
<br />
<SlAlert variant="success" open>
<SlIcon slot="icon" name="check2-circle" />
<strong>Your changes have been saved</strong>
<br />
You can safely exit the app now.
</SlAlert>
<br />
<SlAlert variant="neutral" open>
<SlIcon slot="icon" name="gear" />
<strong>Your settings have been updated</strong>
<br />
Settings will take effect on next login.
</SlAlert>
<br />
<SlAlert variant="warning" open>
<SlIcon slot="icon" name="exclamation-triangle" />
<strong>Your session has ended</strong>
<br />
Please login again to continue.
</SlAlert>
<br />
<SlAlert variant="danger" open>
<SlIcon slot="icon" name="exclamation-octagon" />
<strong>Your account has been deleted</strong>
<br />
We're very sorry to see you go!
</SlAlert>
</>
);
Closable
closable 속성(attribute)을 추가하면 Alert를 숨길 수 있는 닫기 버튼이 표시돼요.
<sl-alert variant="primary" open closable class="alert-closable">
<sl-icon slot="icon" name="info-circle"></sl-icon>
You can close this alert any time!
</sl-alert>
<script>
const alert = document.querySelector('.alert-closable');
alert.addEventListener('sl-after-hide', () => {
setTimeout(() => (alert.open = true), 2000);
});
</script>
import { useState } from 'react';
import SlAlert from '@shoelace-style/shoelace/dist/react/alert';
import SlIcon from '@shoelace-style/shoelace/dist/react/icon';
const App = () => {
const [open, setOpen] = useState(true);
function handleHide() {
setOpen(false);
setTimeout(() => setOpen(true), 2000);
}
return (
<SlAlert open={open} closable onSlAfterHide={handleHide}>
<SlIcon slot="icon" name="info-circle" />
You can close this alert any time!
</SlAlert>
);
};
Without Icons
아이콘은 선택 사항이에요. icon 슬롯을 생략하면 아이콘 없이도 사용할 수 있답니다.
<sl-alert variant="primary" open> Nothing fancy here, just a simple alert. </sl-alert>
import SlAlert from '@shoelace-style/shoelace/dist/react/alert';
const App = () => (
<SlAlert variant="primary" open>
Nothing fancy here, just a simple alert.
</SlAlert>
);
Duration
duration 속성(attribute)을 설정하면 일정 시간이 지난 뒤 Alert가 자동으로 숨겨져요. 확인(acknowledgement)이 필요 없는 알림에 유용하답니다.
<div class="alert-duration">
<sl-button variant="primary">Show Alert</sl-button>
<sl-alert variant="primary" duration="3000" closable>
<sl-icon slot="icon" name="info-circle"></sl-icon>
This alert will automatically hide itself after three seconds, unless you interact with it.
</sl-alert>
</div>
<script>
const container = document.querySelector('.alert-duration');
const button = container.querySelector('sl-button');
const alert = container.querySelector('sl-alert');
button.addEventListener('click', () => alert.show());
</script>
<style>
.alert-duration sl-alert {
margin-top: var(--sl-spacing-medium);
}
</style>
import { useState } from 'react';
import SlAlert from '@shoelace-style/shoelace/dist/react/alert';
import SlButton from '@shoelace-style/shoelace/dist/react/button';
import SlIcon from '@shoelace-style/shoelace/dist/react/icon';
const css = `
.alert-duration sl-alert {
margin-top: var(--sl-spacing-medium);
}
`;
const App = () => {
const [open, setOpen] = useState(false);
return (
<>
<div className="alert-duration">
<SlButton variant="primary" onClick={() => setOpen(true)}>
Show Alert
</SlButton>
<SlAlert variant="primary" duration="3000" open={open} closable onSlAfterHide={() => setOpen(false)}>
<SlIcon slot="icon" name="info-circle" />
This alert will automatically hide itself after three seconds, unless you interact with it.
</SlAlert>
</div>
<style>{css}</style>
</>
);
};
Countdown
countdown 속성(attribute)을 설정하면 Alert가 남은 시간을 알려주는 로딩 바(loading bar)를 표시해요. duration이 비교적 긴 알림에서 유용하답니다.
<div class="alert-countdown">
<sl-button variant="primary">Show Alert</sl-button>
<sl-alert variant="primary" duration="10000" countdown="rtl" closable>
<sl-icon slot="icon" name="info-circle"></sl-icon>
You're not stuck, the alert will close after a pretty long duration.
</sl-alert>
</div>
<script>
const container = document.querySelector('.alert-countdown');
const button = container.querySelector('sl-button');
const alert = container.querySelector('sl-alert');
button.addEventListener('click', () => alert.show());
</script>
<style>
.alert-countdown sl-alert {
margin-top: var(--sl-spacing-medium);
}
</style>
import { useState } from 'react';
import SlAlert from '@shoelace-style/shoelace/dist/react/alert';
import SlButton from '@shoelace-style/shoelace/dist/react/button';
import SlIcon from '@shoelace-style/shoelace/dist/react/icon';
const css = `
.alert-countdown sl-alert {
margin-top: var(--sl-spacing-medium);
}
`;
const App = () => {
const [open, setOpen] = useState(false);
return (
<>
<div className="alert-countdown">
<SlButton variant="primary" onClick={() => setOpen(true)}>
Show Alert
</SlButton>
<SlAlert variant="primary" duration="3000" countdown="rtl" open={open} closable onSlAfterHide={() => setOpen(false)}>
<SlIcon slot="icon" name="info-circle" />
You're not stuck, the alert will close after a pretty long duration.
</SlAlert>
</div>
<style>{css}</style>
</>
);
};
Toast Notifications
Alert를 토스트 알림(Toast)으로 표시하려면 Alert를 만들고 toast() 메서드를 호출하면 돼요. 그러면 Alert가 DOM에서 원래 있던 위치를 벗어나 토스트 스택(toast stack)으로 이동해서 보여지게 돼요. 한번 사라지면 DOM에서 완전히 제거된답니다. 토스트를 재사용하려면 참조(reference)를 저장해 두었다가 나중에 다시 toast()를 호출하면 돼요.
사용자가 알림을 닫을 수 있도록 항상 closable 속성(attribute)을 사용하는 걸 권장해요. 알림에 확인이 필요 없을 때는 합리적인 duration을 설정하는 것도 흔한 패턴이에요.
<div class="alert-toast">
<sl-button variant="primary">Primary</sl-button>
<sl-button variant="success">Success</sl-button>
<sl-button variant="neutral">Neutral</sl-button>
<sl-button variant="warning">Warning</sl-button>
<sl-button variant="danger">Danger</sl-button>
<sl-alert variant="primary" duration="3000" closable>
<sl-icon slot="icon" name="info-circle"></sl-icon>
<strong>This is super informative</strong><br />
You can tell by how pretty the alert is.
</sl-alert>
<sl-alert variant="success" duration="3000" closable>
<sl-icon slot="icon" name="check2-circle"></sl-icon>
<strong>Your changes have been saved</strong><br />
You can safely exit the app now.
</sl-alert>
<sl-alert variant="neutral" duration="3000" closable>
<sl-icon slot="icon" name="gear"></sl-icon>
<strong>Your settings have been updated</strong><br />
Settings will take effect on next login.
</sl-alert>
<sl-alert variant="warning" duration="3000" closable>
<sl-icon slot="icon" name="exclamation-triangle"></sl-icon>
<strong>Your session has ended</strong><br />
Please login again to continue.
</sl-alert>
<sl-alert variant="danger" duration="3000" closable>
<sl-icon slot="icon" name="exclamation-octagon"></sl-icon>
<strong>Your account has been deleted</strong><br />
We're very sorry to see you go!
</sl-alert>
</div>
<script>
const container = document.querySelector('.alert-toast');
['primary', 'success', 'neutral', 'warning', 'danger'].map(variant => {
const button = container.querySelector(`sl-button[variant="${variant}"]`);
const alert = container.querySelector(`sl-alert[variant="${variant}"]`);
button.addEventListener('click', () => alert.toast());
});
</script>
import { useRef } from 'react';
import SlAlert from '@shoelace-style/shoelace/dist/react/alert';
import SlButton from '@shoelace-style/shoelace/dist/react/button';
import SlIcon from '@shoelace-style/shoelace/dist/react/icon';
function showToast(alert) {
alert.toast();
}
const App = () => {
const primary = useRef(null);
const success = useRef(null);
const neutral = useRef(null);
const warning = useRef(null);
const danger = useRef(null);
return (
<>
<SlButton variant="primary" onClick={() => primary.current.toast()}>
Primary
</SlButton>
<SlButton variant="success" onClick={() => success.current.toast()}>
Success
</SlButton>
<SlButton variant="neutral" onClick={() => neutral.current.toast()}>
Neutral
</SlButton>
<SlButton variant="warning" onClick={() => warning.current.toast()}>
Warning
</SlButton>
<SlButton variant="danger" onClick={() => danger.current.toast()}>
Danger
</SlButton>
<SlAlert ref={primary} variant="primary" duration="3000" closable>
<SlIcon slot="icon" name="info-circle" />
<strong>This is super informative</strong>
<br />
You can tell by how pretty the alert is.
</SlAlert>
<SlAlert ref={success} variant="success" duration="3000" closable>
<SlIcon slot="icon" name="check2-circle" />
<strong>Your changes have been saved</strong>
<br />
You can safely exit the app now.
</SlAlert>
<SlAlert ref={neutral} variant="neutral" duration="3000" closable>
<SlIcon slot="icon" name="gear" />
<strong>Your settings have been updated</strong>
<br />
Settings will take effect on next login.
</SlAlert>
<SlAlert ref={warning} variant="warning" duration="3000" closable>
<SlIcon slot="icon" name="exclamation-triangle" />
<strong>Your session has ended</strong>
<br />
Please login again to continue.
</SlAlert>
<SlAlert ref={danger} variant="danger" duration="3000" closable>
<SlIcon slot="icon" name="exclamation-octagon" />
<strong>Your account has been deleted</strong>
<br />
We're very sorry to see you go!
</SlAlert>
</>
);
};
Creating Toasts Imperatively
편의를 위해, HTML에 일일이 조합하지 않고 함수 호출 한 번으로 토스트 알림을 만들어내는 유틸리티를 만들 수도 있어요. 그러려면 아래 예시처럼 JavaScript로 Alert를 생성하고, body에 붙인 다음 toast() 메서드를 호출하면 됩니다.
<div class="alert-toast-wrapper">
<sl-button variant="primary">Create Toast</sl-button>
</div>
<script>
const container = document.querySelector('.alert-toast-wrapper');
const button = container.querySelector('sl-button');
let count = 0;
// Always escape HTML for text arguments!
function escapeHtml(html) {
const div = document.createElement('div');
div.textContent = html;
return div.innerHTML;
}
// Custom function to emit toast notifications
function notify(message, variant = 'primary', icon = 'info-circle', duration = 3000) {
const alert = Object.assign(document.createElement('sl-alert'), {
variant,
closable: true,
duration: duration,
innerHTML: `
<sl-icon name="${icon}" slot="icon"></sl-icon>
${escapeHtml(message)}
`
});
document.body.append(alert);
return alert.toast();
}
button.addEventListener('click', () => {
notify(`This is custom toast #${++count}`);
});
</script>
The Toast Stack
토스트 스택(toast stack)은 Alert 컴포넌트가 내부적으로 만들어 관리하는 고정 위치(fixed position)의 싱글턴(singleton) 요소예요. 토스트가 표시될 때 필요에 따라 DOM에 추가되고 제거된답니다. 토스트가 두 개 이상 보일 때는 토스트 스택 안에서 세로로 쌓여요.
기본적으로 토스트 스택은 뷰포트의 오른쪽 위(top-right)에 위치해요. 스타일시트에서 .sl-toast-stack을 대상으로 지정하면 위치를 바꿀 수 있답니다. 예를 들어 토스트가 뷰포트의 왼쪽 위(top-left)에 나타나게 하려면 다음 스타일을 사용하면 돼요.
.sl-toast-stack {
left: 0;
right: auto;
}
설계상, 토스트를 동시에 두 개 이상의 스택에 표시하는 것은 불가능해요. 그런 동작은 혼란을 주고 사용자 경험을 해치기 때문이에요.
Importing
autoloader나 전통적인 loader를 사용하고 있다면 이 부분은 무시해도 돼요. 그 외의 경우 아래 스니펫 중 하나를 골라 이 컴포넌트만 골라(cherry pick) 가져올 수 있답니다.
Script / Import / Bundler / React
CDN에서 script 태그로 이 컴포넌트를 가져오려면:
<script type="module" src="https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@2.20.1/cdn/components/alert/alert.js"></script>
CDN에서 JavaScript import로 이 컴포넌트를 가져오려면:
import 'https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@2.20.1/cdn/components/alert/alert.js';
bundler를 사용해 이 컴포넌트를 가져오려면:
import '@shoelace-style/shoelace/dist/components/alert/alert.js';
이 컴포넌트를 React 컴포넌트로 가져오려면:
import SlAlert from '@shoelace-style/shoelace/dist/react/alert';
Slots
| Name | Description |
|---|---|
| (default) | The alert’s main content. |
icon |
An icon to show in the alert. Works best with sl-icon. |
슬롯(slots) 사용에 대해 더 알아보기.
Properties
| Name | Description | Reflects | Type | Default |
|---|---|---|---|---|
open |
Indicates whether or not the alert is open. You can toggle this attribute to show and hide the alert, or you can use the show() and hide() methods and this attribute will reflect the alert’s open state. |
boolean |
false |
|
closable |
Enables a close button that allows the user to dismiss the alert. | boolean |
false |
|
variant |
The alert’s theme variant. | 'primary' | 'success' | 'neutral' | 'warning' | 'danger' |
'primary' |
|
duration |
The length of time, in milliseconds, the alert will show before closing itself. If the user interacts with the alert before it closes (e.g. moves the mouse over it), the timer will restart. Defaults to Infinity, meaning the alert will not close on its own. |
- | Infinity |
|
countdown |
Enables a countdown that indicates the remaining time the alert will be displayed. Typically used to indicate the remaining time before a whole app refresh. | 'rtl' | 'ltr' | undefined |
- | |
updateComplete |
A read-only promise that resolves when the component has finished updating. |
속성과 프로퍼티(attributes and properties)에 대해 더 알아보기.
Events
| Name | React Event | Description | Event Detail |
|---|---|---|---|
sl-show |
onSlShow |
Emitted when the alert opens. | - |
sl-after-show |
onSlAfterShow |
Emitted after the alert opens and all animations are complete. | - |
sl-hide |
onSlHide |
Emitted when the alert closes. | - |
sl-after-hide |
onSlAfterHide |
Emitted after the alert closes and all animations are complete. | - |
이벤트(events)에 대해 더 알아보기.
Methods
| Name | Description | Arguments |
|---|---|---|
show() |
Shows the alert. | - |
hide() |
Hides the alert | - |
toast() |
Displays the alert as a toast notification. This will move the alert out of its position in the DOM and, when dismissed, it will be removed from the DOM completely. By storing a reference to the alert, you can reuse it by calling this method again. The returned promise will resolve after the alert is hidden. | - |
메서드(methods)에 대해 더 알아보기.
Parts
| Name | Description |
|---|---|
base |
The component’s base wrapper. |
icon |
The container that wraps the optional icon. |
message |
The container that wraps the alert’s main content. |
close-button |
The close button, an sl-icon-button. |
close-button__base |
The close button’s exported base part. |
CSS 파트(parts) 커스터마이징에 대해 더 알아보기.
Animations
| Name | Description |
|---|---|
alert.show |
The animation to use when showing the alert. |
alert.hide |
The animation to use when hiding the alert. |
애니메이션(animations) 커스터마이징에 대해 더 알아보기.
Dependencies
이 컴포넌트는 다음 의존성들을 자동으로 가져와요.
sl-iconsl-icon-button
더 알아보기 (Learn more)
- Shoelace Button 컴포넌트 — Alert와 함께 자주 쓰는 버튼 문서
- Shoelace Icon 컴포넌트 — Alert의 아이콘 슬롯에서 쓰는 아이콘 문서
- Shoelace 시작하기(getting started) — 컴포넌트 설치와 로딩 방법