Created
July 12, 2023 21:09
-
-
Save dannyhw/f2ec8a356792bae295fe3bf9946285ba to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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