Skip to main content

Accordion

An accordion allows to show and hide a piece of content with a smooth animation. Commonly used in "FAQ" sections.

Loading...

The following implementation of an accordion relies on shared values. Leveraging shared values helps to prevent unnecessary re-renders. We define shared values using the useSharedValue hook.

  const height = useSharedValue(0);

The AccordionItem component encapsulates each item in the accordion. A height shared value manages the height of the item. The height dynamically adjusts based on the isExpanded prop, resulting in smooth expansion and collapse animations. The duration prop controls the duration of the animation.

Inside the AccordionItem, the children represent the content section. It can accommodate various types of content.

Accordion
function AccordionItem({
isExpanded,
children,
viewKey,
style,
duration = 500,
}) {
const height = useSharedValue(0);

const derivedHeight = useDerivedValue(() =>
withTiming(height.value * Number(isExpanded.value), {
duration,
})
);
const bodyStyle = useAnimatedStyle(() => ({
height: derivedHeight.value,
}));

return (
<Animated.View
key={`accordionItem_${viewKey}`}
style={[styles.animatedView, bodyStyle, style]}>
<View
onLayout={(e) => {
height.value = e.nativeEvent.layout.height;
}}
style={styles.wrapper}>
{children}
</View>
</Animated.View>
);
}