Skip to content

[drawer] Create the unstyled Drawer / Sheet component #38

Closed

Description

@michaldudak

This is the place to gather ideas, measure interest and discuss the API and implementation details of the drawer component.

User requests

Benchmarks

Activity

  1. changed the title [-][Drawer][base] Create the unstyled component and hook[/-] [+][Drawer][base-ui] Create the unstyled component and hook[/+] on Aug 18, 2023
  2. changed the title [-][Drawer][base-ui] Create the unstyled component and hook[/-] [+][Drawer] Create the unstyled component and hook[/+] on Feb 27, 2024
  3. added
    type: new feature
    component: drawer
    on Feb 27, 2024
  4. VladimirSamokhin commented on May 22, 2024

    @VladimirSamokhin
  5. MinhMeoNguyen0 commented on Jul 14, 2024

    @MinhMeoNguyen0

    Can you add something that is simliar to this
    image

  6. michaldudak commented on Jul 15, 2024

    @michaldudak
    MemberAuthor

    @MinhMeoNguyen0, this is unrelated to the Drawer component.
    I can imaging a Table of contents component that does this, but we're not currently planning anything along these lines. Feel free to create an issue and we can look into it if there is significant interest from the community.

  7. changed the title [-][Drawer] Create the unstyled component and hook[/-] [+][Drawer] Create the unstyled component[/+] on Nov 6, 2024
  8. borabaloglu commented on Jan 5, 2025

    @borabaloglu

    I implemented a drawer component using dialog component. Here you can find the code and demo here. Are you planning to have something with advanced animations? Otherwise it's like semi-styled dialog component.

  9. michaldudak commented on Jan 6, 2025

    @michaldudak
    MemberAuthor

    We haven't specced it yet. Do you have something specific in mind when referring to "advanced animations"?

  10. borabaloglu commented on Jan 6, 2025

    @borabaloglu

    I implemented the component in a way that feels like a mobile bottom sheet (e.g. https://github.com/gorhom/react-native-bottom-sheet). So it allows user interactions like dragging the drawer up and down, which also allows implementing snap points. What I mean by referring to advanced animations is having animations (drag animation, spring animation, rubber band animation) handled by the unstyled drawer component.

    I don't know how flexible the data-starting-style and data-ending-style are but I couldn't combine these selectors with drag animations.

  11. michaldudak commented on Jan 6, 2025

    @michaldudak
    MemberAuthor

    We're not going to provide any animations out of the box - as the components are unstyled, we can only provide style hooks that you can use to create your own animations. The Dialog component is already flexible enough to enable creating layouts such as mobile navigation on https://base-ui.com, but we'll look into making the most common scenarios easier.

  12. changed the title [-][Drawer] Create the unstyled component[/-] [+][drawer] Create the unstyled component[/+] on Mar 1, 2025
  13. marked [drawer] Implement Drawer #1774 as a duplicate of this issue on Apr 24, 2025
  14. atomiks commented on Apr 24, 2025

    @atomiks
    Contributor

    @michaldudak Most likely similar gestures that Toast has (swipe-movement-x/y). But yeah, currently Dialog can create Drawer-like components with different styles, but there's no gesture support

  15. dartess commented on Apr 28, 2025

    @dartess

    Hello there. I tried to build a Drawer on the Dialog base.

    The regular version works fine, but I have Drawers in my project that are bound to a specific parent. I used the container prop of the Dialog.Portal, and absolute positioning. Everything looks good. But if you click outside the container, the Drawer closes because of <div role="presentation" data-floating-ui-inert="" aria-hidden="true" style="position: fixed; inset: 0px; user-select: none;"></div>. Demo here: https://codesandbox.io/p/devbox/immutable-dew-d8ygkn?workspaceId=ws_8iqbh1gg1GcLonjY38LEti

    While writing this comment I figured out that I could use event and reason to determine if the clicked area and the container are the same. But the solution looks a bit scary:

    const isPressOutsideContainer = (
      event: Event | undefined,
      reason: OpenChangeReason | undefined,
    ): boolean => {
      if (!portalContainer || reason !== 'outside-press' || !(event instanceof MouseEvent)) {
        return false;
      }
      const portalContainerElement =
        portalContainer instanceof HTMLElement ? portalContainer : portalContainer.current;
      if (!portalContainerElement) {
        return false;
      }
      const containerRect = portalContainerElement.getBoundingClientRect();
      const x = event.clientX;
      const y = event.clientY;
      const isPressInside =
        x >= containerRect.left &&
        x <= containerRect.right &&
        y >= containerRect.top &&
        y <= containerRect.bottom;
      return !isPressInside;
    };

    a) can I solve the problem more easily?

    b) my wish for the Drawer component is that this problem is solved out of the box.

    btw to the wishes, to be able to close Drawer as smoothly as Toast, it would be magical. I tried using react-swipeable for this, but I could only use it to add a simple swipe.

  16. colmtuite commented on Apr 28, 2025

    @colmtuite
    Contributor

    We decided today to prioritise this. We'll likely begin working on it in late May.

  17. dartess commented on Apr 28, 2025

    @dartess

    @colmtuite also may be related for Drawer: #1790

  18. isacrasmusson commented on Jun 15, 2025

    @isacrasmusson

    Hey! I forked the code from your MobileNav.css and MobileNav.tsx as a base to build a custom sheet component. It didn’t quite match my needs out of the box, but I adapted it into something that might still be useful to others.

    Changes

    • Uses Tailwind CSS v4
    • Prevents the sheet from visually growing when its content overflows (the internal scroll area expands instead)
    • Sheet can be full height or auto-sized based on content — set via --sheet-height or conditional classes.
    • Uses cn() utility from shadcn for merging class names
    • Adds relevant data-slot attributes for styling/debugging

    To-do / Missing Features

    • Improve keyboard handling on mobile (e.g. adjust for virtual vs visual viewport differences when soft keyboard opens)
    • Support for detents (e.g. snapping the sheet to 50%, 100%, etc.)
    • Desktop support

    Prerequisites

    Make sure to define the following theme variables in your Tailwind config, or replace them with standard easing classes like ease-out and ease-in:

      @theme {
        --ease-out-fast: cubic-bezier(0.45, 1.005, 0, 1.005);
        --ease-in-slow: cubic-bezier(0.375, 0.015, 0.545, 0.455);
      }

    Minimal Component Code

    "use client"
    
    import * as React from "react"
    import { Dialog } from "@base-ui-components/react/dialog"
    
    import { cn } from "@/lib/utils"
    
    type SheetState = {
      setOpen: (state: boolean) => void
    }
    
    const SheetContext = React.createContext<SheetState>({
      setOpen: () => {},
    })
    
    const Sheet = ({ open, onOpenChange, ...props }: Dialog.Root.Props) => {
      const [uncontrolledOpen, setUncontrolledOpen] = React.useState(false)
    
      const controlled = open !== undefined
      const currentOpen = controlled ? open : uncontrolledOpen
      const handleOpenChange = controlled ? onOpenChange! : setUncontrolledOpen
    
      return (
        <SheetContext.Provider value={{ setOpen: handleOpenChange }}>
          <Dialog.Root
            data-slot="sheet"
            open={currentOpen}
            onOpenChange={handleOpenChange}
            {...props}
          />
        </SheetContext.Provider>
      )
    }
    
    const SheetTrigger = ({ ...props }: Dialog.Trigger.Props) => (
      <Dialog.Trigger data-slot="sheet-trigger" {...props} />
    )
    
    const SheetBackdrop = ({ className, ...props }: Dialog.Backdrop.Props) => {
      return (
        <Dialog.Backdrop
          data-slot="sheet-backdrop"
          className={cn(
            "fixed inset-0 h-dvh backdrop-blur-[1.5px]",
    
            "bg-[linear-gradient(to_bottom,_transparent_2rem,_rgb(0_0_0_/_5%)_50%)] dark:bg-[linear-gradient(to_bottom,_transparent,_rgb(0_0_0_/_25%)_6rem)]",
    
            "duration-600 transition-[backdrop-filter,opacity] ease-(--ease-out-fast)",
    
            "data-[starting-style]:backdrop-blur-none data-[starting-style]:opacity-0",
            "data-[ending-style]:backdrop-blur-none data-[ending-style]:opacity-0",
            "data-[ending-style]:ease-(--ease-in-slow) data-[ending-style]:duration-250",
            className
          )}
          {...props}
        />
      )
    }
    
    const SheetPortal = ({ ...props }: Dialog.Portal.Props) => (
      <Dialog.Portal data-slot="SheetPortal" {...props} />
    )
    
    const SheetPopup = ({ className, style, ...props }: Dialog.Popup.Props) => {
      return (
        <Dialog.Popup
          data-slot="sheet-popup"
          style={
            {
              "--viewport-height": "100dvh",
              ...style,
            } as React.CSSProperties
          }
          className={cn(
            "fixed h-(--viewport-height) bottom-0 left-0 w-full outline-0",
            /* Half the transition duration for blur so the element sort of comes into the focus when it's halfway in */
            "duration-[600ms,300ms] transition-[translate,filter] origin-[top_center] ease-(--ease-out-fast)",
    
            "data-[starting-style]:translate-y-(--viewport-height) data-[starting-style]:filter-blur-[1px]",
            "data-ending-style:translate-y-(--viewport-height) data-[ending-style]:filter-blur-[1px]",
    
            /* Delay the blur transition so it doesn't feel unfocused until halway out */
            "data-[ending-style]:delay-[0ms,125ms] data-[ending-style]:ease-(--ease-in-slow) data-[ending-style]:duration-250",
            className
          )}
          {...props}
        >
          <PopupImpl>{props.children}</PopupImpl>
        </Dialog.Popup>
      )
    }
    
    const PopupImpl = ({
      children,
      className,
      style,
      ...props
    }: React.ComponentProps<"div">) => {
      const { setOpen } = React.useContext(SheetContext)
      const rem = React.useRef(16)
    
      React.useEffect(() => {
        rem.current = parseFloat(
          getComputedStyle(document.documentElement).fontSize
        )
      }, [])
    
      // .MobileNavViewport {
      //   &::-webkit-scrollbar {
      //     display: none;
      //   }
      // }
    
      return (
        <div
          data-slot="sheet-viewport"
          style={{
            /* Native apps don't show scrollbars on sheets like this */
            scrollbarWidth: "none",
            ...style,
          }}
          className={cn(
            "absolute inset-0 height-(--viewport-height) overflow-y-auto overscroll-contain",
            className
          )}
          {...props}
     onTouchStart={(event) => {
            const viewport = event.currentTarget
    
            // Consider flicks from scroll top only (iOS does the same with its sheets)
            if (viewport.scrollTop <= 0) {
              viewport.addEventListener(
                "touchend",
     function handleTouchEnd() {
                  // If touch ended and we are overscrolling past a threshold...
                  if (viewport.scrollTop < -16) {
                    const y = viewport.scrollTop
    
                    viewport.addEventListener(
                      "scroll",
                      function handleNextScroll() {
                        // ...look at whether the system's intertia scrolling is continuing the motion
                        // in the same direction. If so, the flick is strong enough to close the dialog.
                        if (viewport.scrollTop < y) {
                          // It's gonna eventually bounce back to scrollTop 0. We need to counteract this
                          // a bit so that the close transition doesn't appear slower than it should.
                          viewport.style.translate = `0px -${y}px`
                          viewport.style.transform = `400ms`
                          setOpen(false)
    
                          // Sometimes the first scroll event comes with the same scroll position
                          // If so, give it another chance, call ourselves recursively
                        } else if (viewport.scrollTop === y) {
                          viewport.addEventListener("scroll", handleNextScroll, {
                            once: true,
                          })
                        }
                      },
                      { once: true }
                    )
                  }
                },
                { once: true }
              )
            }
          }}
        >
          <div
            data-slot="sheet-viewport-inner"
            className={cn(
              "relative isolate min-h-[calc(var(--viewport-height)+1px)]",
              /* Prevent children's margin collapse */
              "flex flex-col"
            )}
          >
            {/* We need the area behind the panel to close on tap but also to scroll the viewport. */}
            <Dialog.Close
              data-slot="sheet-backdrop-tap-area"
              className="absolute inset-0"
              tabIndex={-1}
              render={<div />}
            />
    
            {/* Smoothly hides bottom overscroll edge */}
            <div
              data-slot="sheet-bottom-overscroll"
              className={cn(
                "sticky z-0 top-[100dvh] mb-[-100dvh] h-dvh bg-white dark:bg-gray-800"
              )}
            />
    
            <div
              data-slot="sheet-content"
              style={
                {
                  "--sheet-height": "auto",
                  "--max-sheet-height": "97dvh",
                } as React.CSSProperties
              }
              className={cn(
                "absolute bottom-0 left-0 w-full min-h-24 h-(--sheet-height) max-h-(--max-sheet-height) overflow-hidden p-4 rounded-t-3xl bg-white dark:bg-gray-800",
                className
              )}
            >
              {/* Reverse order to place the close button at the end of the DOM, but at sticky top visually */}
              <div className="flex flex-col-reverse">
                <div>{children}</div>
    
                <div className={cn("sticky top-3 left-full mr-3 h-0 w-fit")}>
                  <Dialog.Close
                    aria-label="Close the navigation"
                    className="MobileNavClose"
                  >
                    Close
                  </Dialog.Close>
                </div>
              </div>
            </div>
          </div>
        </div>
      )
    }
    
    export { Sheet, SheetTrigger, SheetBackdrop, SheetPortal, SheetPopup }

    Complete Component Code

    I have also built a more fleshed out version of the above component that has more componts like SheetToolbar, SheetHeader, SheetScroller and so on. This allows the sheet to behave more like a native ios sheet with a scrollable main portion where the sheet is always dismissible by dragging the header. I'll set up a repo if anyone is interested.

  19. dartess commented on Jul 15, 2025

    @dartess

    It would be great to have something like positionMethod='fixed' | 'absolute'. Due to how the Dialog is implemented, it's difficult to make the Drawer use absolute instead of fixed. In my case, I had to pass a container to the Portal through several layers of components, but even then, when the Drawer opens, an invisible overlay still covers the entire screen — even though the Drawer is positioned and rendered within a specific panel.

  20. changed the title [-][drawer] Create the unstyled component[/-] [+][drawer] Create the unstyled Drawer / Sheet component[/+] on Jan 17, 2026
  21. moved this from Future to Recently completed in Base UI public roadmapon Feb 12, 2026
  22. github-actions commented on Feb 12, 2026

    @github-actions

    This feature will be available in the next npm release of Base UI.

    In the meantime, you can try it out on our Canary release channel:

    npm i https://pkg.pr.new/@base-ui/react@3680
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    component: drawertype: new feature

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions