본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

드로어 (Drawer)

원문 보기 위키 갱신

드로어(Drawer)는 컨테이너 가장자리에서 슬라이드로 들어와 추가 옵션이나 정보를 펼쳐 보여주는 컴포넌트예요. 화면 옆에 붙는 사이드 패널처럼, 눈에 거슬리지 않게 필요한 내용을 꺼내 보여줄 때 딱 맞아요. _ | SlDrawer 컴포넌트는 Shoelace 2.0부터 제공되고 있으며 stable 상태예요.

출처: 문서

본문

| SlDrawer — Since 2.0, stable

드로어(Drawer)는 컨테이너 가장자리에서 슬라이드로 들어와 추가 옵션과 정보를 보여줘요.

<sl-drawer label="Drawer" class="drawer-overview">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit.
  <sl-button slot="footer" variant="primary">Close</sl-button>
</sl-drawer>
<sl-button>Open Drawer</sl-button>
<script>
  const drawer = document.querySelector('.drawer-overview');
  const openButton = drawer.nextElementSibling;
  const closeButton = drawer.querySelector('sl-button[variant="primary"]');
  openButton.addEventListener('click', () => drawer.show());
  closeButton.addEventListener('click', () => drawer.hide());
</script>

React로도 똑같이 쓸 수 있어요. open prop과 onSlAfterHide 이벤트로 상태를 관리하면 돼요.

import { useState } from 'react';
import SlButton from '@shoelace-style/shoelace/dist/react/button';
import SlDrawer from '@shoelace-style/shoelace/dist/react/drawer';
const App = () => {
  const [open, setOpen] = useState(false);
  return (
    <>
      <SlDrawer label="Drawer" open={open} onSlAfterHide={() => setOpen(false)}>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit.
        <SlButton slot="footer" variant="primary" onClick={() => setOpen(false)}>
          Close
        </SlButton>
      </SlDrawer>
      <SlButton onClick={() => setOpen(true)}>Open Drawer</SlButton>
    </>
  );
};

Examples

Slide in From Start

기본적으로 드로어는 끝(end) 쪽에서 슬라이드로 들어와요. 시작(start) 쪽에서 슬라이드로 들어오게 하려면 placement 속성을 start로 설정하면 돼요.

<sl-drawer label="Drawer" placement="start" class="drawer-placement-start">
  This drawer slides in from the start.
  <sl-button slot="footer" variant="primary">Close</sl-button>
</sl-drawer>
<sl-button>Open Drawer</sl-button>
<script>
  const drawer = document.querySelector('.drawer-placement-start');
  const openButton = drawer.nextElementSibling;
  const closeButton = drawer.querySelector('sl-button[variant="primary"]');
  openButton.addEventListener('click', () => drawer.show());
  closeButton.addEventListener('click', () => drawer.hide());
</script>
import { useState } from 'react';
import SlButton from '@shoelace-style/shoelace/dist/react/button';
import SlDrawer from '@shoelace-style/shoelace/dist/react/drawer';
const App = () => {
  const [open, setOpen] = useState(false);
  return (
    <>
      <SlDrawer label="Drawer" placement="start" open={open} onSlAfterHide={() => setOpen(false)}>
        This drawer slides in from the start.
        <SlButton slot="footer" variant="primary" onClick={() => setOpen(false)}>
          Close
        </SlButton>
      </SlDrawer>
      <SlButton onClick={() => setOpen(true)}>Open Drawer</SlButton>
    </>
  );
};

Slide in From Top

드로어가 위(top)에서 슬라이드로 들어오게 하려면 placement 속성을 top으로 설정하면 돼요.

<sl-drawer label="Drawer" placement="top" class="drawer-placement-top">
  This drawer slides in from the top.
  <sl-button slot="footer" variant="primary">Close</sl-button>
</sl-drawer>
<sl-button>Open Drawer</sl-button>
<script>
  const drawer = document.querySelector('.drawer-placement-top');
  const openButton = drawer.nextElementSibling;
  const closeButton = drawer.querySelector('sl-button[variant="primary"]');
  openButton.addEventListener('click', () => drawer.show());
  closeButton.addEventListener('click', () => drawer.hide());
</script>
import { useState } from 'react';
import SlButton from '@shoelace-style/shoelace/dist/react/button';
import SlDrawer from '@shoelace-style/shoelace/dist/react/drawer';
const App = () => {
  const [open, setOpen] = useState(false);
  return (
    <>
      <SlDrawer label="Drawer" placement="top" open={open} onSlAfterHide={() => setOpen(false)}>
        This drawer slides in from the top.
        <SlButton slot="footer" variant="primary" onClick={() => setOpen(false)}>
          Close
        </SlButton>
      </SlDrawer>
      <SlButton onClick={() => setOpen(true)}>Open Drawer</SlButton>
    </>
  );
};

Slide in From Bottom

드로어가 아래(bottom)에서 슬라이드로 들어오게 하려면 placement 속성을 bottom으로 설정하면 돼요.

<sl-drawer label="Drawer" placement="bottom" class="drawer-placement-bottom">
  This drawer slides in from the bottom.
  <sl-button slot="footer" variant="primary">Close</sl-button>
</sl-drawer>
<sl-button>Open Drawer</sl-button>
<script>
  const drawer = document.querySelector('.drawer-placement-bottom');
  const openButton = drawer.nextElementSibling;
  const closeButton = drawer.querySelector('sl-button[variant="primary"]');
  openButton.addEventListener('click', () => drawer.show());
  closeButton.addEventListener('click', () => drawer.hide());
</script>
import { useState } from 'react';
import SlButton from '@shoelace-style/shoelace/dist/react/button';
import SlDrawer from '@shoelace-style/shoelace/dist/react/drawer';
const App = () => {
  const [open, setOpen] = useState(false);
  return (
    <>
      <SlDrawer label="Drawer" placement="bottom" open={open} onSlAfterHide={() => setOpen(false)}>
        This drawer slides in from the bottom.
        <SlButton slot="footer" variant="primary" onClick={() => setOpen(false)}>
          Close
        </SlButton>
      </SlDrawer>
      <SlButton onClick={() => setOpen(true)}>Open Drawer</SlButton>
    </>
  );
};

Contained to an Element

기본적으로 드로어는 자신의 containing block, 즉 보통은 뷰포트에서 밖으로 슬라이드돼요. 부모 요소에서 밖으로 슬라이드하게 만들고 싶다면 드로어에 contained 속성을 추가하고, 부모 요소에 position: relative를 적용하면 되요.

일반 드로어와 달리 contained 드로어는 모달(modal)이 아니에요. 즉 오버레이를 보여주지 않고, 포커스를 가두지(trap) 않으며, Escape 키로 닫히지도 않아요. 사용자가 드로어 바깥의 요소와도 자유롭게 상호작용할 수 있도록 의도적으로 설계된 동작이에요.

<div
  style="position: relative; border: solid 2px var(--sl-panel-border-color); height: 300px; padding: 1rem; margin-bottom: 1rem;"
>
  The drawer will be contained to this box. This content won't shift or be affected in any way when the drawer opens.
  <sl-drawer label="Drawer" contained class="drawer-contained" style="--size: 50%;">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    <sl-button slot="footer" variant="primary">Close</sl-button>
  </sl-drawer>
</div>
<sl-button>Toggle Drawer</sl-button>
<script>
  const drawer = document.querySelector('.drawer-contained');
  const openButton = drawer.parentElement.nextElementSibling;
  const closeButton = drawer.querySelector('sl-button[variant="primary"]');
  openButton.addEventListener('click', () => (drawer.open = !drawer.open));
  closeButton.addEventListener('click', () => drawer.hide());
</script>
import { useState } from 'react';
import SlButton from '@shoelace-style/shoelace/dist/react/button';
import SlDrawer from '@shoelace-style/shoelace/dist/react/drawer';
const App = () => {
  const [open, setOpen] = useState(false);
  return (
    <>
      <div
        style={{
          position: 'relative',
          border: 'solid 2px var(--sl-panel-border-color)',
          height: '300px',
          padding: '1rem',
          marginBottom: '1rem'
        }}
      >
        The drawer will be contained to this box. This content won't shift or be affected in any way when the drawer
        opens.
        <SlDrawer
          label="Drawer"
          contained
          no-modal
          open={open}
          onSlAfterHide={() => setOpen(false)}
          style={{ '--size': '50%' }}
        >
          Lorem ipsum dolor sit amet, consectetur adipiscing elit.
          <SlButton slot="footer" variant="primary" onClick={() => setOpen(false)}>
            Close
          </SlButton>
        </SlDrawer>
      </div>
      <SlButton onClick={() => setOpen(true)}>Open Drawer</SlButton>
    </>
  );
};

Custom Size

--size 커스텀 프로퍼티로 드로어의 크기를 정할 수 있어요. 이 값은 placement에 따라 드로어의 너비 또는 높이에 적용돼요.

<sl-drawer label="Drawer" class="drawer-custom-size" style="--size: 50vw;">
  This drawer is always 50% of the viewport.
  <sl-button slot="footer" variant="primary">Close</sl-button>
</sl-drawer>
<sl-button>Open Drawer</sl-button>
<script>
  const drawer = document.querySelector('.drawer-custom-size');
  const openButton = drawer.nextElementSibling;
  const closeButton = drawer.querySelector('sl-button[variant="primary"]');
  openButton.addEventListener('click', () => drawer.show());
  closeButton.addEventListener('click', () => drawer.hide());
</script>
import { useState } from 'react';
import SlButton from '@shoelace-style/shoelace/dist/react/button';
import SlDrawer from '@shoelace-style/shoelace/dist/react/drawer';
const App = () => {
  const [open, setOpen] = useState(false);
  return (
    <>
      <SlDrawer label="Drawer" open={open} onSlAfterHide={() => setOpen(false)} style={{ '--size': '50vw' }}>
        This drawer is always 50% of the viewport.
        <SlButton slot="footer" variant="primary" onClick={() => setOpen(false)}>
          Close
        </SlButton>
      </SlDrawer>
      <SlButton onClick={() => setOpen(true)}>Open Drawer</SlButton>
    </>
  );
};

Scrolling

설계상 드로어의 높이는 컨테이너의 100%를 절대 넘지 않아요. 그래서 헤더와 푸터가 항상 사용자에게 보이도록, 드로어는 페이지와 함께 스크롤되지 않아요.

<sl-drawer label="Drawer" class="drawer-scrolling">
  <div style="height: 150vh; border: dashed 2px var(--sl-color-neutral-200); padding: 0 1rem;">
    <p>Scroll down and give it a try! 👇</p>
  </div>
  <sl-button slot="footer" variant="primary">Close</sl-button>
</sl-drawer>
<sl-button>Open Drawer</sl-button>
<script>
  const drawer = document.querySelector('.drawer-scrolling');
  const openButton = drawer.nextElementSibling;
  const closeButton = drawer.querySelector('sl-button[variant="primary"]');
  openButton.addEventListener('click', () => drawer.show());
  closeButton.addEventListener('click', () => drawer.hide());
</script>
import { useState } from 'react';
import SlButton from '@shoelace-style/shoelace/dist/react/button';
import SlDrawer from '@shoelace-style/shoelace/dist/react/drawer';
const App = () => {
  const [open, setOpen] = useState(false);
  return (
    <>
      <SlDrawer label="Drawer" open={open} onSlAfterHide={() => setOpen(false)}>
        <div
          style={{
            height: '150vh',
            border: 'dashed 2px var(--sl-color-neutral-200)',
            padding: '0 1rem'
          }}
        >
          <p>Scroll down and give it a try! 👇</p>
        </div>
        <SlButton slot="footer" variant="primary" onClick={() => setOpen(false)}>
          Close
        </SlButton>
      </SlDrawer>
      <SlButton onClick={() => setOpen(true)}>Open Drawer</SlButton>
    </>
  );
};

Header Actions

헤더에는 기본적으로 동작하는 닫기 버튼이 있어요. 필요하다면 header-actions 슬롯에 추가 아이콘 버튼을 넣을 수도 있어요.

<sl-drawer label="Drawer" class="drawer-header-actions">
  <sl-icon-button class="new-window" slot="header-actions" name="box-arrow-up-right"></sl-icon-button>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit.
  <sl-button slot="footer" variant="primary">Close</sl-button>
</sl-drawer>
<sl-button>Open Drawer</sl-button>
<script>
  const drawer = document.querySelector('.drawer-header-actions');
  const openButton = drawer.nextElementSibling;
  const closeButton = drawer.querySelector('sl-button[variant="primary"]');
  const newWindowButton = drawer.querySelector('.new-window');
  openButton.addEventListener('click', () => drawer.show());
  closeButton.addEventListener('click', () => drawer.hide());
  newWindowButton.addEventListener('click', () => window.open(location.href));
</script>
import { useState } from 'react';
import SlButton from '@shoelace-style/shoelace/dist/react/button';
import SlDrawer from '@shoelace-style/shoelace/dist/react/drawer';
import SlIconButton from '@shoelace-style/shoelace/dist/react/icon-button';
const App = () => {
  const [open, setOpen] = useState(false);
  return (
    <>
      <SlDrawer label="Drawer" open={open} onSlAfterHide={() => setOpen(false)}>
        <SlIconButton slot="header-actions" name="box-arrow-up-right" onClick={() => window.open(location.href)} />
        Lorem ipsum dolor sit amet, consectetur adipiscing elit.
        <SlButton slot="footer" variant="primary" onClick={() => setOpen(false)}>
          Close
        </SlButton>
      </SlDrawer>
      <SlButton onClick={() => setOpen(true)}>Open Drawer</SlButton>
    </>
  );
};

Preventing the Drawer from Closing

기본적으로 드로어는 사용자가 닫기 버튼을 클릭하거나, 오버레이를 클릭하거나, Escape 키를 누르면 닫혀요. 대부분의 경우 UX 관점에서 기본 동작이 가장 좋은 동작이에요. 하지만 데이터 손실이 발생할 수 있는 상황처럼, 닫히면 곤란한 경우도 있어요.

그런 경우에는 sl-request-close 이벤트를 취소하면 드로어를 계속 열어둘 수 있어요. 이벤트가 취소되면 드로어는 닫히지 않고, 사용자에게 주의를 끌기 위해 잠깐 펄스(pulse) 애니메이션을 보여줘요.

event.detail.source로 어떤 동작이 닫기 요청을 발생시켰는지 알 수 있어요. 아래 예제는 오버레이를 클릭했을 때는 드로어가 닫히지 않도록 막지만, 닫기 버튼이나 Escape 키로는 닫히도록 허용한답니다.

<sl-drawer label="Drawer" class="drawer-deny-close">
  This drawer will not close when you click on the overlay.
  <sl-button slot="footer" variant="primary">Close</sl-button>
</sl-drawer>
<sl-button>Open Drawer</sl-button>
<script>
  const drawer = document.querySelector('.drawer-deny-close');
  const openButton = drawer.nextElementSibling;
  const closeButton = drawer.querySelector('sl-button[variant="primary"]');
  openButton.addEventListener('click', () => drawer.show());
  closeButton.addEventListener('click', () => drawer.hide());
  // Prevent the drawer from closing when the user clicks on the overlay
  drawer.addEventListener('sl-request-close', event => {
    if (event.detail.source === 'overlay') {
      event.preventDefault();
    }
  });
</script>
import { useState } from 'react';
import SlButton from '@shoelace-style/shoelace/dist/react/button';
import SlDrawer from '@shoelace-style/shoelace/dist/react/drawer';
const App = () => {
  const [open, setOpen] = useState(false);
  // Prevent the drawer from closing when the user clicks on the overlay
  function handleRequestClose(event) {
    if (event.detail.source === 'overlay') {
      event.preventDefault();
    }
  }
  return (
    <>
      <SlDrawer label="Drawer" open={open} onSlRequestClose={handleRequestClose} onSlAfterHide={() => setOpen(false)}>
        This drawer will not close when you click on the overlay.
        <SlButton slot="footer" variant="primary" onClick={() => setOpen(false)}>
          Save &amp; Close
        </SlButton>
      </SlDrawer>
      <SlButton onClick={() => setOpen(true)}>Open Drawer</SlButton>
    </>
  );
};

Customizing Initial Focus

기본적으로 드로어가 열리면 드로어의 패널에 포커스가 가요. 그러면 그다음 Tab 키를 누를 때 드로어 안의 첫 번째 tabbable 요소로 포커스가 이동해요. 다른 요소에 포커스를 두고 싶다면, 아래처럼 그 요소에 autofocus 속성을 추가하면 되요.

<sl-drawer label="Drawer" class="drawer-focus">
  <sl-input autofocus placeholder="I will have focus when the drawer is opened"></sl-input>
  <sl-button slot="footer" variant="primary">Close</sl-button>
</sl-drawer>
<sl-button>Open Drawer</sl-button>
<script>
  const drawer = document.querySelector('.drawer-focus');
  const input = drawer.querySelector('sl-input');
  const openButton = drawer.nextElementSibling;
  const closeButton = drawer.querySelector('sl-button[variant="primary"]');
  openButton.addEventListener('click', () => drawer.show());
  closeButton.addEventListener('click', () => drawer.hide());
</script>
import { useState } from 'react';
import SlButton from '@shoelace-style/shoelace/dist/react/button';
import SlDrawer from '@shoelace-style/shoelace/dist/react/drawer';
import SlInput from '@shoelace-style/shoelace/dist/react/input';
const App = () => {
  const [open, setOpen] = useState(false);
  return (
    <>
      <SlDrawer label="Drawer" open={open} onSlAfterHide={() => setOpen(false)}>
        <SlInput autofocus placeholder="I will have focus when the drawer is opened" />
        <SlButton slot="footer" variant="primary" onClick={() => setOpen(false)}>
          Close
        </SlButton>
      </SlDrawer>
      <SlButton onClick={() => setOpen(true)}>Open Drawer</SlButton>
    </>
  );
};

초기 포커스 동작을 더 세밀하게 조정하고 싶다면, sl-initial-focus 이벤트를 취소하고 이벤트 핸들러 안에서 직접 포커스를 설정하면 되요.

Importing

autoloader나 전통적인 loader를 사용하고 있다면 이 부분은 건너뛰어도 돼요. 그 외에는 아래 스니펫 중 원하는 걸 골라 이 컴포넌트만 골라 가져올 수 있어요.

Script / Import / Bundler / React 방식이 준비되어 있어요.

CDN에서 <script> 태그로 이 컴포넌트를 가져오려면:

<script type="module" src="https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@2.20.1/cdn/components/drawer/drawer.js"></script>

CDN에서 JavaScript import로 가져오려면:

import 'https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@2.20.1/cdn/components/drawer/drawer.js';

Bundler를 사용해 가져오려면:

import '@shoelace-style/shoelace/dist/components/drawer/drawer.js';

React 컴포넌트로 가져오려면:

import SlDrawer from '@shoelace-style/shoelace/dist/react/drawer';

Slots

Name Description
(default) The drawer’s main content.
label The drawer’s label. Alternatively, you can use the label attribute.
header-actions Optional actions to add to the header. Works best with ``.
footer The drawer’s footer, usually one or more buttons representing various options.

슬롯 사용법에 대해 더 알아보세요.

Properties

Name Description Reflects Type Default
modal Exposes the internal modal utility that controls focus trapping. To temporarily disable focus
                trapping and allow third-party modals spawned from an active Shoelace modal, call
                `modal.activateExternal()` when the third-party modal opens. Upon closing, call
                `modal.deactivateExternal()` to restore Shoelace’s focus trapping. |  | - | `new Modal(this)` |

| open | Indicates whether or not the drawer is open. You can toggle this attribute to show and hide the drawer, or you can use the show() and hide() methods and this attribute will reflect the drawer’s open state. | | boolean | false | | label | The drawer’s label as displayed in the header. You should always include a relevant label even when using no-header, as it is required for proper accessibility. If you need to display HTML, use the label slot instead. | | string | '' | | placement | The direction from which the drawer will open. | | 'top' \| 'end' \| 'bottom' \| 'start' | 'end' | | contained | By default, the drawer slides out of its containing block (usually the viewport). To make the drawer slide out of its parent element, set this attribute and add position: relative to the parent. | | boolean | false | | noHeader no-header | Removes the header. This will also remove the default close button, so please ensure you provide an easy, accessible way for users to dismiss the drawer. | | boolean | false | | updateComplete | A read-only promise that resolves when the component has finished updating. | | | |

속성과 프로퍼티에 대해 더 알아보세요.

Events

Name React Event Description Event Detail
sl-show onSlShow Emitted when the drawer opens. -
sl-after-show onSlAfterShow Emitted after the drawer opens and all animations are complete. -
sl-hide onSlHide Emitted when the drawer closes. -
sl-after-hide onSlAfterHide Emitted after the drawer closes and all animations are complete. -
sl-initial-focus onSlInitialFocus Emitted when the drawer opens and is ready to receive focus. Calling
                `event.preventDefault()` will prevent focusing and allow you to set it on a different
                element, such as an input. | - |

| sl-request-close | onSlRequestClose | Emitted when the user attempts to close the drawer by clicking the close button, clicking the overlay, or pressing escape. Calling event.preventDefault() will keep the drawer open. Avoid using this unless closing the drawer will result in destructive behavior such as data loss. | { source: 'close-button' \| 'keyboard' \| 'overlay' } |

이벤트에 대해 더 알아보세요.

Methods

Name Description Arguments
show() Shows the drawer. -
hide() Hides the drawer -

메서드에 대해 더 알아보세요.

Custom Properties

Name Description Default
--size The preferred size of the drawer. This will be applied to the drawer’s width or height depending on
its placement. Note that the drawer will shrink to accommodate smaller screens.
--header-spacing The amount of padding to use for the header.
--body-spacing The amount of padding to use for the body.
--footer-spacing The amount of padding to use for the footer.

CSS 커스텀 프로퍼티 커스터마이징에 대해 더 알아보세요.

Parts

Name Description
base The component’s base wrapper.
overlay The overlay that covers the screen behind the drawer.
panel The drawer’s panel (where the drawer and its content are rendered).
header The drawer’s header. This element wraps the title and header actions.
header-actions Optional actions to add to the header. Works best with ``.
title The drawer’s title.
close-button The close button, an ``.
close-button__base The close button’s exported base part.
body The drawer’s body.
footer The drawer’s footer.

CSS 파트 커스터마이징에 대해 더 알아보세요.

Animations

Name Description
drawer.showTop The animation to use when showing a drawer with top placement.
drawer.showEnd The animation to use when showing a drawer with end placement.
drawer.showBottom The animation to use when showing a drawer with bottom placement.
drawer.showStart The animation to use when showing a drawer with start placement.
drawer.hideTop The animation to use when hiding a drawer with top placement.
drawer.hideEnd The animation to use when hiding a drawer with end placement.
drawer.hideBottom The animation to use when hiding a drawer with bottom placement.
drawer.hideStart The animation to use when hiding a drawer with start placement.
drawer.denyClose The animation to use when a request to close the drawer is denied.
drawer.overlay.show The animation to use when showing the drawer’s overlay.
drawer.overlay.hide The animation to use when hiding the drawer’s overlay.

애니메이션 커스터마이징에 대해 더 알아보세요.

Dependencies

이 컴포넌트는 다음 의존성들을 자동으로 가져와요.

  • ``
  • ``

더 알아보기 (Learn more)