Skip to content

Instantly share code, notes, and snippets.

@dannyhw
Created July 12, 2023 21:09
Show Gist options
  • Save dannyhw/f2ec8a356792bae295fe3bf9946285ba to your computer and use it in GitHub Desktop.
Save dannyhw/f2ec8a356792bae295fe3bf9946285ba to your computer and use it in GitHub Desktop.
import Animated, {
useAnimatedStyle,
useSharedValue,
withTiming,
} from "react-native-reanimated";
export const CollapsableContainer = ({
children,
expanded,
}: {
children: React.ReactNode;
expanded: boolean;
}) => {
const [height, setHeight] = useState(0);
const animatedHeight = useSharedValue(0);
const onLayout = (event: LayoutChangeEvent) => {
const onLayoutHeight = event.nativeEvent.layout.height;
if (onLayoutHeight > 0 && height !== onLayoutHeight) {
setHeight(onLayoutHeight);
}
};
const collapsableStyle = useAnimatedStyle(() => {
animatedHeight.value = expanded ? withTiming(height) : withTiming(0);
return {
height: animatedHeight.value,
};
}, [expanded]);
return (
<Animated.View style={[collapsableStyle, { overflow: "hidden" }]}>
<View style={{ position: "absolute" }} onLayout={onLayout}>
{children}
</View>
</Animated.View>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment