Skip to content

Utils Primitive

A collection of utilities for core primitives.

Installation

Copy/paste the following code to ~/components/primitives/utils.tsx

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 '~/components/primitives/hooks';
import type { PressableRef, SlottablePressableProps } from '~/components/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 '~/components/primitives/hooks';
import type { PressableRef, SlottablePressableProps } from '~/components/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} />
);
}
);