Skip to main content

useItemContext

Overview

The useItemContext hook provides context with useful item-related values.

Usage

import { useItemContext } from 'react-native-sortables';

const ctx = useItemContext(); // inside a sortable item component

Return Values

The useItemContext hook returns an object with the following properties:

  • itemKey - key of the item where the hook is called
  • activeItemKey - key of the currently active item
  • prevActiveItemKey - key of the previously active item
  • isActive - whether the item is currently being dragged
  • dragActivationState - current drag activation state of the sortable component
  • activationAnimationProgress - progress of the activation animation (0 to 1) of the currently active item
Type definitions
type ItemContextType = {
itemKey: string;
activeItemKey: Readonly<SharedValue<null | string>>;
prevActiveItemKey: Readonly<SharedValue<null | string>>;
isActive: Readonly<SharedValue<boolean>>;
dragActivationState: Readonly<SharedValue<DragActivationState>>;
activationAnimationProgress: Readonly<SharedValue<number>>;
};

Example

Here's an example of how to use the useItemContext hook to create a custom item component that responds to drag states:

function GridItem({ item }: { item: string }) {
const { activationAnimationProgress, dragActivationState } = useItemContext();

const colorStyle = useAnimatedStyle(() => ({
backgroundColor: interpolateColor(
activationAnimationProgress.value,
[0, 1],
['#36877F', '#063934']
)
}));

const shakeStyle = useAnimatedStyle(() => {
const easeOut = Easing.out(Easing.quad);

return {
transform: [
dragActivationState.value === DragActivationState.ACTIVE
? {
rotate: withSequence(
withTiming('0.08rad', { duration: 80, easing: Easing.linear }),
withTiming('-0.08rad', { duration: 80, easing: Easing.linear }),
withTiming('0.08rad', { duration: 80, easing: Easing.linear }),
withTiming('-0.06rad', { duration: 80, easing: Easing.linear }),
withTiming('0.06rad', { duration: 80, easing: Easing.linear }),
withTiming('-0.04rad', { duration: 80, easing: Easing.linear }),
withTiming('0.04rad', { duration: 80, easing: Easing.linear }),
withTiming('0rad', { duration: 100, easing: easeOut })
)
}
: { rotate: withTiming('0rad', { duration: 100, easing: easeOut }) }
]
};
});

return (
<Animated.View style={[styles.card, colorStyle, shakeStyle]}>
<Text style={styles.text}>{item}</Text>
</Animated.View>
);
}

Result

Remarks

  • The useItemContext hook must be used within a component that is rendered as part of a sortable item.
info

If you need to access other values, please request them in the GitHub Discussions. There are other properties that can be exposed in the ItemContextType type.