Skip to content

Commit 593e2eb

Browse files
fix[Android]: tab width changes on changes in values (#721)
1 parent e75ebfa commit 593e2eb

File tree

1 file changed

+20
-7
lines changed

1 file changed

+20
-7
lines changed

js/SegmentedControl.js

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ const SegmentedControl = ({
4343
const colorScheme = appearance || colorSchemeHook;
4444
const [segmentWidth, setSegmentWidth] = React.useState(0);
4545
const animation = React.useRef(new Animated.Value(0)).current;
46+
const ref = React.useRef();
4647

4748
const handleChange = (index: number) => {
4849
// mocks iOS's nativeEvent
@@ -56,6 +57,17 @@ const SegmentedControl = ({
5657
onValueChange && onValueChange(values[index]);
5758
};
5859

60+
const updateSegmentWidth = React.useCallback(
61+
(width: number) => {
62+
const newSegmentWidth = values.length ? width / values.length : 0;
63+
if (newSegmentWidth !== segmentWidth) {
64+
animation.setValue(newSegmentWidth * (selectedIndex || 0));
65+
setSegmentWidth(newSegmentWidth);
66+
}
67+
},
68+
[values.length, segmentWidth, animation, selectedIndex],
69+
);
70+
5971
React.useEffect(() => {
6072
if (animation && segmentWidth) {
6173
let isRTL = I18nManager.isRTL ? -segmentWidth : segmentWidth;
@@ -68,8 +80,15 @@ const SegmentedControl = ({
6880
}
6981
}, [animation, segmentWidth, selectedIndex]);
7082

83+
React.useEffect(() => {
84+
if (ref.current) {
85+
ref.current.measure((_x, _y, width) => updateSegmentWidth(width));
86+
}
87+
}, [values]);
88+
7189
return (
7290
<View
91+
ref={ref}
7392
style={[
7493
styles.default,
7594
style,
@@ -81,13 +100,7 @@ const SegmentedControl = ({
81100
nativeEvent: {
82101
layout: {width},
83102
},
84-
}) => {
85-
const newSegmentWidth = values.length ? width / values.length : 0;
86-
if (newSegmentWidth !== segmentWidth) {
87-
animation.setValue(newSegmentWidth * (selectedIndex || 0));
88-
setSegmentWidth(newSegmentWidth);
89-
}
90-
}}>
103+
}) => updateSegmentWidth(width)}>
91104
{!backgroundColor && !tintColor && (
92105
<SegmentsSeparators
93106
values={values.length}

0 commit comments

Comments
 (0)