# Bottom Sheet
URL: /react/stackflow/bottom-sheet
Source: https://github.com/daangn/seed-design/blob/dev/docs/content/react/stackflow/bottom-sheet.mdx
Guide to using Bottom Sheet with Stackflow.
사용 가능 버전: @seed-design/stackflow@1.1.5, @seed-design/css@1.1.5
Learn more about the Bottom Sheet component.
## Making a Bottom Sheet Activity
**In typical cases, it is recommended to create a Bottom Sheet as an [Activity](https://stackflow.so/docs/get-started/activity) and use it.**
- Since it is managed as an Activity, it is easy to manage with z-index higher than lower Activities and lower than upper Activities.
- Deep linking is possible. (You can open the Bottom Sheet by accessing a URL.)
- Migration from [@stackflow/plugin-basic-ui](https://www.npmjs.com/package/@stackflow/plugin-basic-ui) `BottomSheet` is easy.
```tsx title='ActivityBottomSheetActivity.tsx'
import { VStack } from "@seed-design/react";
import { useFlow, type StaticActivityComponentType } from "@stackflow/react/future";
import {
AppBar,
AppBarBackButton,
AppBarLeft,
AppBarMain,
AppBarIconButton,
AppBarRight,
} from "seed-design/ui/app-bar";
import { AppScreen, AppScreenContent } from "seed-design/ui/app-screen";
import { ActionButton } from "seed-design/ui/action-button";
import { IconHouseLine } from "@karrotmarket/react-monochrome-icon";
declare module "@stackflow/config" {
interface Register {
ActivityBottomSheetActivity: {};
}
}
const ActivityBottomSheetActivity: StaticActivityComponentType<
"ActivityBottomSheetActivity"
> = () => {
const { push } = useFlow();
return (
push("ActivityHome", {})}>
push("ActivityBottomSheet", {})}
>
ActivityBottomSheet을 Push
push("ActivityBottomSheetActivity", {})}
>
지금 열린 이 Activity를 Push
);
};
export default ActivityBottomSheetActivity;
```
```tsx title='ActivityBottomSheet.tsx'
import { Divider, HStack, VStack } from "@seed-design/react";
import { useActivity, useFlow, type StaticActivityComponentType } from "@stackflow/react/future";
import { useRef, useState } from "react";
import { ActionButton } from "seed-design/ui/action-button";
import {
BottomSheetBody,
BottomSheetContent,
BottomSheetFooter,
BottomSheetRoot,
} from "seed-design/ui/bottom-sheet";
import { Checkbox } from "seed-design/ui/checkbox";
import { Snackbar, useSnackbarAdapter } from "seed-design/ui/snackbar";
import { TextField, TextFieldInput } from "seed-design/ui/text-field";
import { useActivityZIndexBase } from "@seed-design/stackflow";
import { Switch } from "seed-design/ui/switch";
import { Chip } from "seed-design/ui/chip";
import { appScreenVariantMap, type AppScreenVariant } from "@seed-design/css/recipes/app-screen";
declare module "@stackflow/config" {
interface Register {
ActivityBottomSheet: {};
}
}
const ActivityBottomSheet: StaticActivityComponentType<"ActivityBottomSheet"> = () => {
const { push, pop } = useFlow();
const activity = useActivity();
const form = useRef(null);
const snackbar = useSnackbarAdapter();
const [nameError, setNameError] = useState(null);
const [keepMounted, setKeepMounted] = useState(false);
const [transitionStyle, setTransitionStyle] =
useState("slideFromRightIOS");
const handleSubmit = () => {
if (!form.current) return;
const formData = new FormData(form.current);
if (!formData.get("name")) {
setNameError("이름을 입력해주세요.");
return;
}
setNameError(null);
pop();
snackbar.create({
render: () => (
),
});
};
const open = keepMounted
? activity.transitionState === "enter-active" || activity.transitionState === "enter-done"
: activity.isActive;
const onOpenChange = keepMounted
? (open: boolean) => !open && activity.isActive && pop()
: (open: boolean) => !open && pop();
return (
);
};
export default ActivityBottomSheet;
```
### Usage
```tsx
import { useActivityZIndexBase } from "@seed-design/stackflow";
import { useActivity, useFlow, type ActivityComponentType } from "@stackflow/react/future";
// ... more imports
const ActivityBottomSheetSimple: ActivityComponentType<"ActivityBottomSheetSimple"> = () => {
const { pop } = useFlow();
return (
{/* [!code highlight] */}
!open && pop()}>
Confirm
);
};
```
1. Pass `useActivity().isActive` to the `open` prop so that the Bottom Sheet opens when the Activity is activated.
2. When the Bottom Sheet closes, run `pop()` through `onOpenChange` to terminate the Activity.
3. Pass the z-index base point of the Bottom Sheet Activity with `layerIndex={useActivityZIndexBase()}`.
- [Learn more about `useActivityZIndexBase`](#about-useactivityzindexbase)
#### Keeping Bottom Sheet Mounted
To prevent the Bottom Sheet from being unmounted when pushing another Activity on top of the Bottom Sheet Activity:
- Manage the `open` state with `transitionState` instead of `isActive`
- Set the `modal` prop to `isActive`
- Execute `pop()` in the `onOpenChange` handler when `!isOpen && isActive`.
This pattern is useful in the following situations:
- When you want to nest and display another overlay component Activity on top of the Bottom Sheet Activity
- When you want to maintain the state of uncontrolled form elements that exist inside the lower Bottom Sheet Activity
```tsx
const { isActive, transitionState } = useActivity();
return (
!open && isActive && pop()}
>
{/* ... */}
);
```
1. Manage `open` with `transitionState` so that the Bottom Sheet is not unmounted even when another Activity is pushed on top.
2. Set `modal` to `false` when the Bottom Sheet Activity is inactive with `modal={isActive}`. If you don't do this, interactions such as focus, screen reader access, and scrolling will not work in the Activity pushed above.
3. Execute `pop()` only when `isActive` in the `onOpenChange` handler to prevent unintended Activity termination in an inactive state.
#### Stacking Another Modal Overlay on Top
When pushing another modal Activity with its own backdrop (e.g., Alert Dialog Activity) on top of the Bottom Sheet Activity, it is recommended to always set `modal` to `true` instead of `modal={isActive}`.
The `modal={isActive}` pattern is to ensure interactions such as scrolling when the Activity pushed above is a normal AppScreen, but if the Activity pushed above is a modal overlay with its own backdrop, the backdrop of the Bottom Sheet may disappear at the point of becoming inactive, which can make the dim layering appear broken.
```tsx title='ActivityNestedBottomSheet.tsx'
import { VStack } from "@seed-design/react";
import { useActivityZIndexBase } from "@seed-design/stackflow";
import { useActivity, useFlow, type StaticActivityComponentType } from "@stackflow/react/future";
import { ActionButton } from "seed-design/ui/action-button";
import {
BottomSheetBody,
BottomSheetContent,
BottomSheetFooter,
BottomSheetRoot,
} from "seed-design/ui/bottom-sheet";
import { Callout } from "seed-design/ui/callout";
declare module "@stackflow/config" {
interface Register {
ActivityNestedBottomSheet: {};
}
}
const ActivityNestedBottomSheet: StaticActivityComponentType<"ActivityNestedBottomSheet"> = () => {
const { pop, push } = useFlow();
const { isActive, transitionState } = useActivity();
const open = transitionState === "enter-active" || transitionState === "enter-done";
const onOpenChange = (next: boolean) => !next && isActive && pop();
return (
// 위에 AlertDialog Activity가 push되어 BottomSheet가 비활성(isActive=false)이 되더라도
// BottomSheet 자체의 modal 동작과 backdrop을 유지해 dim layering이 끊기지 않도록 modal을 항상 true로 둔다.
// outside close는 onOpenChange에서 isActive 가드로 막혀 비활성 상태에서는 pop이 발생하지 않는다.
push("ActivityAlertDialog", {})}
>
Open AlertDialog
닫기
);
};
export default ActivityNestedBottomSheet;
```
```tsx
const { isActive, transitionState } = useActivity();
return (
!open && isActive && pop()}
>
{/* ... */}
);
```
1. Keep `modal` always `true` so that the Bottom Sheet's backdrop layering is not broken even when another modal Activity is pushed above.
2. Thanks to the `isActive` guard in `onOpenChange`, `pop()` does not occur unintentionally from outside interactions in an inactive state.
If the Activity pushed above is a normal AppScreen that does not have a backdrop covering the Bottom Sheet area, the `modal={isActive}` guide is appropriate for interactions such as scrolling in the above Activity. Use the variation where `modal` is always `true` only when two modal overlays are stacked.
## Syncing BottomSheet State with a Step
If you cannot create a Bottom Sheet as an Activity, you can create the state where the Bottom Sheet is displayed as a [Step](https://stackflow.so/docs/get-started/navigating-step).
- You can close the Bottom Sheet with a back button, etc., while maintaining the current Activity.
- You can open and close the Bottom Sheet using `BottomSheetTrigger`.
**Before pushing another Activity from a Bottom Sheet not created as an Activity, close the Bottom Sheet to prevent z-index issues.**
If you cannot close the Bottom Sheet, or if you need to maintain the Bottom Sheet in an open state when returning to the Activity that opened it, it is recommended to [create the Bottom Sheet as an Activity](#making-a-bottom-sheet-activity).
To provide smooth transitions between Activities, some lower AppScreen elements are positioned above upper AppScreen elements. Due to this constraint, an open Bottom Sheet cannot be positioned between lower and upper Activities unless it is created as an independent Activity.
```tsx title='ActivityBottomSheetStep.tsx'
import { HStack, Portal, VStack } from "@seed-design/react";
import { useActivityZIndexBase } from "@seed-design/stackflow";
import {
useActivityParams,
useFlow,
useStepFlow,
type StaticActivityComponentType,
} from "@stackflow/react/future";
import { useEffect, useState } from "react";
import { ActionButton } from "seed-design/ui/action-button";
import { AppBar, AppBarMain, AppBarIconButton, AppBarRight } from "seed-design/ui/app-bar";
import { AppScreen, AppScreenContent } from "seed-design/ui/app-screen";
import { IconHouseLine } from "@karrotmarket/react-monochrome-icon";
import {
BottomSheetContent,
BottomSheetFooter,
BottomSheetRoot,
BottomSheetTrigger,
} from "seed-design/ui/bottom-sheet";
declare module "@stackflow/config" {
interface Register {
ActivityBottomSheetStep: {
"bottom-sheet"?: "open";
};
}
}
const ActivityBottomSheetStep: StaticActivityComponentType<"ActivityBottomSheetStep"> = () => {
const [open, setOpen] = useState(false);
const { push } = useFlow();
const { pushStep, popStep } = useStepFlow("ActivityBottomSheetStep");
const params = useActivityParams<"ActivityBottomSheetStep">();
const isOverlayOpen = params["bottom-sheet"] === "open";
useEffect(() => setOpen(isOverlayOpen), [isOverlayOpen]);
const onOpenChange = (newOpen: boolean) => {
setOpen(newOpen);
if (newOpen && !isOverlayOpen) {
pushStep((params) => ({ ...params, "bottom-sheet": "open" }));
return;
}
if (!newOpen && isOverlayOpen) {
popStep();
return;
}
};
return (
push("ActivityHome", {})}>
Bottom Sheet 열기
setOpen(false)} variant="neutralWeak">
닫기
{
// 이 Bottom Sheet는 Activity로 만들어지지 않았기 때문에, z-index 정리를 위해
// BottomSheet를 먼저 닫고 다음 Activity를 push해야 합니다.
setOpen(false);
push("ActivityDetail", {
title: "Bottom Sheet에서 이동한 화면",
body: "Bottom Sheet를 닫고 이동했습니다.",
});
}}
>
Push
);
};
export default ActivityBottomSheetStep;
```
### Usage
```tsx
import { useActivityZIndexBase } from "@seed-design/stackflow";
import { Portal } from "@seed-design/react";
import {
useActivity,
useActivityParams,
useFlow,
useStepFlow,
type ActivityComponentType,
} from "@stackflow/react/future";
import { useEffect, useState } from "react";
// ... more imports
declare module "@stackflow/config" {
interface Register {
ActivityHome: {
"bottom-sheet"?: "open";
};
}
}
const ActivityHome: ActivityComponentType<"ActivityHome"> = () => {
const [open, setOpen] = useState(false);
const { push } = useFlow();
const { pushStep, popStep } = useStepFlow("ActivityHome");
const params = useActivityParams<"ActivityHome">();
// [!code highlight]
const isOverlayOpen = params["bottom-sheet"] === "open";
// [!code highlight]
useEffect(() => {
if (!isOverlayOpen) {
setOpen(false);
}
}, [isOverlayOpen]);
// [!code highlight]
const onOpenChange = (newOpen: boolean) => {
setOpen(newOpen);
if (newOpen && !isOverlayOpen) {
pushStep((params) => ({ ...params, "bottom-sheet": "open" }));
return;
}
if (!newOpen && isOverlayOpen) {
popStep();
return;
}
};
return (
Open
{/* [!code highlight] */}
setOpen(false)}>Cancel
{
// [!code highlight]
setOpen(false); // Close the Bottom Sheet before moving to another Activity.
push("ActivityNext");
}}
>
Next
{/* [!code highlight] */}
);
};
```
1. Use `Portal` to render the Bottom Sheet outside the current Activity in the DOM.
2. Manage the `open` prop and synchronize the Step state through the `onOpenChange` handler.
3. Synchronize the `open` state of the Bottom Sheet when Activity parameters change through back button, etc.
4. Pass a z-index base point one level higher than the current Activity with `layerIndex={useActivityZIndexBase({ activityOffset: 1 })}`.
- [Learn more about `useActivityZIndexBase`](#about-useactivityzindexbase)
### `useStepOverlay`
It is convenient to use `useStepOverlay` to generalize #2 and #3. For implementation examples of `useStepOverlay`, see the [code](https://github.com/daangn/seed-design/blob/dev/examples/stackflow-spa/src/seed-design/stackflow/use-step-overlay.ts).
```tsx
import { useActivityZIndexBase } from "@seed-design/stackflow";
import { Portal } from "@seed-design/react";
import { useStepOverlay } from "./use-step-overlay";
// ... more imports
const MyActivity: ActivityComponentType = () => {
// [!code highlight]
const { overlayProps, setOpen } = useStepOverlay();
const { popStep } = useStepFlow("MyActivity");
const { push } = useFlow();
return (
{/* [!code highlight] */}
Open
{/* [!code highlight] */}
setOpen(false)}>Cancel
{
// [!code highlight]
setOpen(false); // Close the Bottom Sheet before moving to another Activity.
push("ActivityNext");
}}
>
Next
{/* [!code highlight] */}
);
};
```
## About `useActivityZIndexBase`
`useActivityZIndexBase` is a hook that returns the z-index base point for each Activity.
- It returns `useActivity().zIndex * 5`. `useActivity().zIndex` is a value indicating which Activity the current Activity is among the entered Activities.
- Elements that make up AppScreen (layer, appbar, dim, edge) have z-index calculated based on the `useActivityZIndexBase()` value.
```
┌─ 2nd BottomSheet Activity
│ └─ BottomSheet: 12 (2 × 5 + 2)
├─ 1st AppScreen Activity
│ ├─ appbar: 12 (1 × 5 + 7)
│ ├─ edge: 9 (1 × 5 + 4)
│ ├─ layer: 7 (1 × 5 + 2)
│ └─ dim: 5 (1 × 5 + 0)
└─ 0th AppScreen Activity
├─ appbar: 7 (0 × 5 + 7)
├─ edge: 4 (0 × 5 + 4)
├─ layer: 2 (0 × 5 + 2)
└─ dim: 0 (0 × 5 + 0)
```
- The `activityOffset` option is used when you want to use the z-index base point of the next Activity instead of the current Activity.
- For example, `useActivityZIndexBase({ activityOffset: 1 })` returns the z-index base point of the next Activity.
- This is useful when displaying a BottomSheet on top of the current Activity in the Step pattern.
```
┌─ BottomSheet displayed with activityOffset: 1 from 1st AppScreen Activity (e.g., Step pattern)
│ └─ BottomSheet: 12 ((1 + 1) × 5 + 2)
├─ 1st AppScreen Activity
│ ├─ appbar: 12 (1 × 5 + 7)
│ ├─ edge: 9 (1 × 5 + 4)
│ ├─ layer: 7 (1 × 5 + 2)
│ └─ dim: 5 (1 × 5 + 0)
└─ 0th AppScreen Activity
├─ appbar: 7 (0 × 5 + 7)
├─ edge: 4 (0 × 5 + 4)
├─ layer: 2 (0 × 5 + 2)
└─ dim: 0 (0 × 5 + 0)
```
- Both hooks return values needed for z-index styling based on which Activity the current Activity is among the entered Activities.
- While the values returned by both hooks are the same, when using Crispy components instead of [@stackflow/plugin-basic-ui](https://www.npmjs.com/package/@stackflow/plugin-basic-ui), it is recommended to use the `useActivityZIndexBase` hook from the `@seed-design/stackflow` package managed by Crispy.
- The `useActivityZIndexBase` hook in the `@stackflow/react-ui-core` package does not provide the `activityOffset` option.
- The `useActivityZIndexBase` hook is provided starting from `@seed-design/stackflow@1.1.1`.
If you were specifying `layerIndex` in the form `useActivity().zIndex * 5 + n`, you can change it to `useActivityZIndexBase() + n`. As you make the change, also review whether `+ n` is necessary.