Skip to content

Utils Primitive

A collection of utilities for core primitives.

Utilities

  • ToggleGroupUtils: Utilities related to primitives with a toggle group.
  • EmptyGestureResponderEvent: Used for calling onPress and onLongPress without any arguments for accessibility purposes.

Installation

Install the component via your command line.

Terminal window
npx expo install @rn-primitives/utils

Usage

ToggleGroupUtils

  • getIsSelected: Returns true if the item is selected.
  • getNewSingleValue: Returns the new value for a single toggle group.
  • getNewMultipleValue: Returns the new value for a multiple toggle group.
import { ToggleGroupUtils } from '@rn-primitives/hooks';
import type { PressableRef, SlottablePressableProps } from '@rn-primitives/types';
const Item = React.forwardRef<PressableRef, SlottablePressableProps>(
(
{ value: itemValue, onPress: onPressProp, ...props },
ref
) => {
const { type, value, onValueChange } = useRootContext();
function onPress(ev: GestureResponderEvent) {
if (type === 'single') {
onValueChange(ToggleGroupUtils.getNewSingleValue(value, itemValue));
}
if (type === 'multiple') {
onValueChange(ToggleGroupUtils.getNewMultipleValue(value, itemValue));
}
onPressProp?.(ev);
}
const isChecked =
type === 'single' ? ToggleGroupUtils.getIsSelected(value, itemValue) : undefined;
const isSelected =
type === 'multiple' ? ToggleGroupUtils.getIsSelected(value, itemValue) : undefined;
return (
<Pressable
ref={ref}
role={type === 'single' ? 'radio' : 'checkbox'}
onPress={onPress}
aria-checked={isChecked}
aria-selected={isSelected}
accessibilityState={{
checked: isChecked,
selected: isSelected,
}}
{...props}
/>
</ItemContext.Provider>
);
}
);

EmptyGestureResponderEvent

import { EmptyGestureResponderEvent } from '@rn-primitives/hooks';
import type { PressableRef, SlottablePressableProps } from '@rn-primitives/types';
const Item = React.forwardRef<PressableRef, SlottablePressableProps>(
({ onPress: onPressProp, onKeyDown: onKeyDownProp, ...props }, ref) => {
function onKeyDown(ev: React.KeyboardEvent) {
if (ev.key === 'Enter' || ev.key === ' ') {
onKeyDownProp?.(ev);
onPressProp?.(EmptyGestureResponderEvent);
console.log("onKeyDown Enter or Space");
}
}
function onPress(ev: GestureResponderEvent) {
onPressProp?.(ev);
console.log("onPress");
}
const Component = asChild ? Slot.Pressable : Pressable;
return (
<Pressable ref={ref} onPress={onPress} onKeyDown={onKeyDown} {...props} />
);
}
);