UIPackage React Native
Search

Context Menu

Touch-ready context-menu with composable actions, checked choices, submenus, and portal positioning.

Install

First install? Set up the registry in your app.

npx --yes --package=https://native.uipkge.dev/cli/uipkge-native-0.1.1.tgz uipkge-native add context-menu

Source files

Expand a file to read the source the installer copies into your app.

components/ui/context-menu/SubContentPrimitive.tsx
export { SubContent as SubContentPrimitive } from '@rn-primitives/context-menu'
components/ui/context-menu/SubContentPrimitive.web.tsx
import * as React from 'react'
import { Pressable, type PressableStateCallbackType } from 'react-native'
import { Slot } from '@rn-primitives/slot'
import type { SubContentProps, SubContentRef } from '@rn-primitives/context-menu'
import * as Radix from '@radix-ui/react-context-menu'

// The registry wrapper owns the scoped Portal; RN Primitives 1.5.2 adds an implicit body portal on web.
export const SubContentPrimitive = React.forwardRef<SubContentRef, SubContentProps & { className?: string }>(
  ({ asChild = false, forceMount, style, ...props }, ref) => {
    const Component = asChild ? Slot : Pressable
    const bounds = { width: '100%', maxWidth: '100%', minWidth: 0 } as const
    return (
      <Radix.SubContent
        forceMount={forceMount}
        avoidCollisions
        collisionPadding={8}
        style={{
          width: 320,
          maxWidth: 'min(calc(100vw - 16px), var(--radix-context-menu-content-available-width, 320px))',
          maxHeight: 'min(calc(100vh - 16px), var(--radix-context-menu-content-available-height, 100vh))',
          overflowX: 'hidden',
          overflowY: 'auto',
        }}
      >
        <Component
          ref={ref}
          {...props}
          style={
            typeof style === 'function'
              ? (state: PressableStateCallbackType) => [bounds, style(state)]
              : [bounds, style]
          }
        />
      </Radix.SubContent>
    )
  },
)
SubContentPrimitive.displayName = 'context-menu-SubContentPrimitive'
components/ui/context-menu/ContextMenu.tsx
import * as React from 'react'
import { Platform, ScrollView, StyleSheet, View, I18nManager, useWindowDimensions } from 'react-native'
import * as Primitive from '@rn-primitives/context-menu'
import { cssInterop } from 'react-native-css-interop'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
import { PortalWindow, usePopupDismiss, PopupLayer } from '@/lib/portal'
import { renderTextChildren } from '@/lib/label-children'
import { cn } from '@/lib/utils'
import { Check, ChevronRight } from 'lucide-react-native'
import { useThemeColors } from '@/lib/theme'
import { SubContentPrimitive } from './SubContentPrimitive'

cssInterop(Primitive.Root, { className: 'style' })
cssInterop(Primitive.Trigger, { className: 'style' })
cssInterop(Primitive.Content, { className: 'style' })
cssInterop(Primitive.Overlay, { className: 'style' })
cssInterop(Primitive.Item, { className: 'style' })
cssInterop(Primitive.Group, { className: 'style' })
cssInterop(Primitive.Label, { className: 'style' })
cssInterop(Primitive.CheckboxItem, { className: 'style' })
cssInterop(Primitive.RadioGroup, { className: 'style' })
cssInterop(Primitive.RadioItem, { className: 'style' })
cssInterop(Primitive.ItemIndicator, { className: 'style' })
cssInterop(Primitive.Separator, { className: 'style' })
cssInterop(Primitive.Sub, { className: 'style' })
cssInterop(Primitive.SubTrigger, { className: 'style' })
cssInterop(SubContentPrimitive, { className: 'style' })

export type ContextMenuProps = Primitive.RootProps & { className?: string }

export const ContextMenu = React.forwardRef<Primitive.RootRef, ContextMenuProps>(({ className, ...props }, ref) => (
  <Primitive.Root ref={ref} className={cn('self-start', className)} {...props} />
))
ContextMenu.displayName = 'ContextMenu'
export type ContextMenuTriggerProps = Omit<Primitive.TriggerProps, 'children'> & {
  children?: React.ReactNode
  className?: string
  /** Native tap opens the same actions as long press; web keeps its context-menu gesture. */
  openOnPress?: boolean
}
export const ContextMenuTrigger = React.forwardRef<Primitive.TriggerRef, ContextMenuTriggerProps>(
  ({ className, children, asChild, disabled, onPress, openOnPress = true, ...props }, ref) => {
    const trigger = React.useRef<Primitive.TriggerRef>(null)
    const setRef = React.useCallback(
      (node: Primitive.TriggerRef | null) => {
        trigger.current = node
        if (typeof ref === 'function') return ref(node)
        if (ref) ref.current = node
      },
      [ref],
    )
    return (
      <Primitive.Trigger
        accessibilityRole="button"
        {...props}
        ref={setRef}
        asChild={asChild}
        disabled={disabled}
        onPress={(event) => {
          if (disabled) return
          onPress?.(event)
          if (Platform.OS !== 'web' && openOnPress && !event.isDefaultPrevented()) trigger.current?.open()
        }}
        className={cn(
          'min-h-[48px] min-w-[48px] flex-row items-center justify-center gap-[8px] rounded-md border border-border bg-background px-[16px] py-[10px] active:bg-accent',
          disabled && 'opacity-50',
          className,
        )}
      >
        {asChild ? children : renderTextChildren(children)}
      </Primitive.Trigger>
    )
  },
)
ContextMenuTrigger.displayName = 'ContextMenuTrigger'
export type ContextMenuContentProps = Omit<Primitive.ContentProps, 'children'> & {
  children?: React.ReactNode
  className?: string
}
export const ContextMenuContent = React.forwardRef<Primitive.ContentRef, ContextMenuContentProps>(
  (
    { className, children, asChild, insets, style, align = 'start', side = 'bottom', sideOffset = 8, ...props },
    ref,
  ) => {
    const root = Primitive.useRootContext()
    const visible = root.open
    const popup = usePopupDismiss(visible, () => root.onOpenChange(false))
    const safe = useSafeAreaInsets()
    const { width, height } = useWindowDimensions()
    const bounds = { top: safe.top + 8, bottom: safe.bottom + 8, left: safe.left + 8, right: safe.right + 8, ...insets }
    const maxWidth = Math.max(0, Math.min(320, width - bounds.left - bounds.right))
    const maxHeight = Math.max(0, height - bounds.top - bounds.bottom)
    // Native headless content must unmount to release its platform Back subscription.
    if (Platform.OS !== 'web' && !visible) return null
    return (
      <Primitive.Portal
        forceMount={props.forceMount}
        hostName={popup.hostName}
        {...(Platform.OS === 'web'
          ? { container: (popup.container ?? undefined) as unknown as Primitive.PortalProps['container'] }
          : {})}
      >
        <PortalWindow layer={popup}>
          {Platform.OS !== 'web' ? <Primitive.Overlay accessible={false} style={StyleSheet.absoluteFill} /> : null}
          <Primitive.Content
            {...props}
            ref={ref}
            asChild={asChild}
            align={align}
            side={side}
            sideOffset={sideOffset}
            insets={bounds}
            className={cn('gap-[4px] rounded-lg border border-border bg-popover p-[8px]', className)}
            style={
              StyleSheet.flatten([
                { maxWidth, maxHeight, ...(Platform.OS !== 'web' ? { width: maxWidth } : {}) },
                style,
              ]) ?? undefined
            }
          >
            {asChild ? (
              children
            ) : (
              <ScrollView bounces={false} keyboardShouldPersistTaps="handled" style={{ maxHeight, flexGrow: 0 }}>
                {renderTextChildren(children)}
              </ScrollView>
            )}
          </Primitive.Content>
        </PortalWindow>
      </Primitive.Portal>
    )
  },
)
ContextMenuContent.displayName = 'ContextMenuContent'
export type ContextMenuItemProps = Omit<Primitive.ItemProps, 'children'> & {
  children?: React.ReactNode
  className?: string
}
export const ContextMenuItem = React.forwardRef<Primitive.ItemRef, ContextMenuItemProps>(
  ({ className, children, asChild, disabled, ...props }, ref) => (
    <Primitive.Item
      {...props}
      ref={ref}
      asChild={asChild}
      disabled={disabled}
      className={cn(
        'min-h-[48px] min-w-[48px] flex-row items-center gap-[8px] rounded-md px-[12px] py-[10px] active:bg-accent',
        disabled && 'opacity-50',
        className,
      )}
    >
      {asChild ? children : <View className="min-w-0 flex-1">{renderTextChildren(children)}</View>}
    </Primitive.Item>
  ),
)
ContextMenuItem.displayName = 'ContextMenuItem'
export type ContextMenuGroupProps = Primitive.GroupProps & { className?: string }
export const ContextMenuGroup = React.forwardRef<Primitive.GroupRef, ContextMenuGroupProps>(
  ({ className, ...props }, ref) => <Primitive.Group ref={ref} className={cn('gap-[4px]', className)} {...props} />,
)
ContextMenuGroup.displayName = 'ContextMenuGroup'
export type ContextMenuSeparatorProps = Primitive.SeparatorProps & { className?: string }
export const ContextMenuSeparator = React.forwardRef<Primitive.SeparatorRef, ContextMenuSeparatorProps>(
  ({ className, ...props }, ref) => (
    <Primitive.Separator ref={ref} className={cn('my-[4px] h-[1px] bg-border', className)} {...props} />
  ),
)
ContextMenuSeparator.displayName = 'ContextMenuSeparator'
export type ContextMenuLabelProps = Primitive.LabelProps & { className?: string }
export const ContextMenuLabel = React.forwardRef<Primitive.LabelRef, ContextMenuLabelProps>(
  ({ className, ...props }, ref) => (
    <Primitive.Label
      ref={ref}
      className={cn('px-[12px] py-[8px] text-[15px] font-medium leading-[21px] text-muted-foreground', className)}
      {...props}
    />
  ),
)
ContextMenuLabel.displayName = 'ContextMenuLabel'
export type ContextMenuItemIndicatorProps = Primitive.ItemIndicatorProps & { className?: string }
export const ContextMenuItemIndicator = React.forwardRef<Primitive.ItemIndicatorRef, ContextMenuItemIndicatorProps>(
  ({ className, children, asChild, ...props }, ref) => {
    const colors = useThemeColors()
    return (
      <Primitive.ItemIndicator
        ref={ref}
        asChild={asChild}
        className={cn('size-[20px] items-center justify-center', className)}
        {...props}
      >
        {asChild ? children : (children ?? <Check size={18} color={colors.foreground} aria-hidden />)}
      </Primitive.ItemIndicator>
    )
  },
)
ContextMenuItemIndicator.displayName = 'ContextMenuItemIndicator'
export type ContextMenuCheckboxItemProps = Omit<Primitive.CheckboxItemProps, 'children'> & {
  children?: React.ReactNode
  className?: string
}
export const ContextMenuCheckboxItem = React.forwardRef<Primitive.CheckboxItemRef, ContextMenuCheckboxItemProps>(
  ({ className, children, asChild, disabled, ...props }, ref) => (
    <Primitive.CheckboxItem
      {...props}
      ref={ref}
      asChild={asChild}
      disabled={disabled}
      className={cn(
        'min-h-[48px] min-w-[48px] flex-row items-center gap-[8px] rounded-md px-[12px] py-[10px] active:bg-accent',
        disabled && 'opacity-50',
        className,
      )}
    >
      {asChild ? (
        children
      ) : (
        <>
          <View aria-hidden className="size-[20px] items-center justify-center">
            <ContextMenuItemIndicator />
          </View>
          <View className="min-w-0 flex-1">{renderTextChildren(children)}</View>
        </>
      )}
    </Primitive.CheckboxItem>
  ),
)
ContextMenuCheckboxItem.displayName = 'ContextMenuCheckboxItem'
export type ContextMenuRadioItemProps = Omit<Primitive.RadioItemProps, 'children'> & {
  children?: React.ReactNode
  className?: string
}
export const ContextMenuRadioItem = React.forwardRef<Primitive.RadioItemRef, ContextMenuRadioItemProps>(
  ({ className, children, asChild, disabled, ...props }, ref) => (
    <Primitive.RadioItem
      {...props}
      ref={ref}
      asChild={asChild}
      disabled={disabled}
      className={cn(
        'min-h-[48px] min-w-[48px] flex-row items-center gap-[8px] rounded-md px-[12px] py-[10px] active:bg-accent',
        disabled && 'opacity-50',
        className,
      )}
    >
      {asChild ? (
        children
      ) : (
        <>
          <View aria-hidden className="size-[20px] items-center justify-center">
            <ContextMenuItemIndicator />
          </View>
          <View className="min-w-0 flex-1">{renderTextChildren(children)}</View>
        </>
      )}
    </Primitive.RadioItem>
  ),
)
ContextMenuRadioItem.displayName = 'ContextMenuRadioItem'
export const ContextMenuRadioGroup = Primitive.RadioGroup
export const ContextMenuSub = Primitive.Sub
export type ContextMenuSubTriggerProps = Omit<Primitive.SubTriggerProps, 'children'> & {
  children?: React.ReactNode
  className?: string
}
export const ContextMenuSubTrigger = React.forwardRef<Primitive.SubTriggerRef, ContextMenuSubTriggerProps>(
  ({ className, children, asChild, disabled, ...props }, ref) => {
    const colors = useThemeColors()
    return (
      <Primitive.SubTrigger
        ref={ref}
        asChild={asChild}
        disabled={disabled}
        className={cn(
          'min-h-[48px] min-w-[48px] flex-row items-center gap-[8px] rounded-md px-[12px] py-[10px] active:bg-accent',
          disabled && 'opacity-50',
          className,
        )}
        {...props}
      >
        {asChild ? (
          children
        ) : (
          <>
            <View className="min-w-0 flex-1">{renderTextChildren(children)}</View>
            <ChevronRight
              size={20}
              color={colors.foreground}
              style={{ transform: [{ scaleX: I18nManager.isRTL ? -1 : 1 }] }}
              aria-hidden
            />
          </>
        )}
      </Primitive.SubTrigger>
    )
  },
)
ContextMenuSubTrigger.displayName = 'ContextMenuSubTrigger'

export type ContextMenuSubContentProps = Omit<Primitive.SubContentProps, 'children'> & {
  children?: React.ReactNode
  className?: string
}
export const ContextMenuSubContent = React.forwardRef<Primitive.SubContentRef, ContextMenuSubContentProps>(
  ({ className, children, asChild, ...props }, ref) => {
    const root = Primitive.useRootContext()
    const sub = Primitive.useSubContext()
    const visible = root.open && sub.open
    const popup = usePopupDismiss(visible, () => sub.onOpenChange(false))
    if (Platform.OS !== 'web' && !visible) return null
    const content = (
      <SubContentPrimitive
        ref={ref}
        asChild={asChild}
        className={cn('gap-[4px] rounded-lg border border-border bg-popover p-[8px]', className)}
        {...props}
      >
        {asChild ? children : renderTextChildren(children)}
      </SubContentPrimitive>
    )
    return (
      <PopupLayer layer={popup}>
        {Platform.OS === 'web' ? (
          <Primitive.Portal
            forceMount={props.forceMount}
            hostName={popup.hostName}
            {...(Platform.OS === 'web'
              ? { container: (popup.container ?? undefined) as unknown as Primitive.PortalProps['container'] }
              : {})}
          >
            {content}
          </Primitive.Portal>
        ) : (
          content
        )}
      </PopupLayer>
    )
  },
)
ContextMenuSubContent.displayName = 'ContextMenuSubContent'
components/ui/context-menu/index.ts
export * from './ContextMenu'

Dependencies

Registry items

npm packages

  • @rn-primitives/slot
  • @radix-ui/react-context-menu@^2.2.16
  • @rn-primitives/context-menu
  • react-native-safe-area-context
  • lucide-react-native
  • react-native-svg
  • react-native-css-interop
Browse overlays and feedback