diff --git a/js/SegmentedControl.js b/js/SegmentedControl.js index d82ecb5f..621d3f6c 100644 --- a/js/SegmentedControl.js +++ b/js/SegmentedControl.js @@ -41,6 +41,7 @@ const SegmentedControl = ({ const colorScheme = appearance || colorSchemeHook; const [segmentWidth, setSegmentWidth] = React.useState(0); const animation = React.useRef(new Animated.Value(0)).current; + const ref = React.useRef(); const handleChange = (index: number) => { // mocks iOS's nativeEvent @@ -54,6 +55,17 @@ const SegmentedControl = ({ onValueChange && onValueChange(values[index]); }; + const updateSegmentWidth = React.useCallback( + (width: number) => { + const newSegmentWidth = values.length ? width / values.length : 0; + if (newSegmentWidth !== segmentWidth) { + animation.setValue(newSegmentWidth * (selectedIndex || 0)); + setSegmentWidth(newSegmentWidth); + } + }, + [values.length, segmentWidth, animation, selectedIndex], + ); + React.useEffect(() => { if (animation && segmentWidth) { let isRTL = I18nManager.isRTL ? -segmentWidth : segmentWidth; @@ -66,8 +78,15 @@ const SegmentedControl = ({ } }, [animation, segmentWidth, selectedIndex]); + React.useEffect(() => { + if (ref.current) { + ref.current.measure((_x, _y, width) => updateSegmentWidth(width)); + } + }, [values]); + return ( { - const newSegmentWidth = values.length ? width / values.length : 0; - if (newSegmentWidth !== segmentWidth) { - animation.setValue(newSegmentWidth * (selectedIndex || 0)); - setSegmentWidth(newSegmentWidth); - } - }}> + }) => updateSegmentWidth(width)}> {!backgroundColor && !tintColor && (