Skip to content

Commit

Permalink
fix[Android]: tab width changes on changes in values (#721)
Browse files Browse the repository at this point in the history
  • Loading branch information
pranshuchittora authored Oct 23, 2024
1 parent e75ebfa commit 593e2eb
Showing 1 changed file with 20 additions and 7 deletions.
27 changes: 20 additions & 7 deletions js/SegmentedControl.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,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
Expand All @@ -56,6 +57,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;
Expand All @@ -68,8 +80,15 @@ const SegmentedControl = ({
}
}, [animation, segmentWidth, selectedIndex]);

React.useEffect(() => {
if (ref.current) {
ref.current.measure((_x, _y, width) => updateSegmentWidth(width));
}
}, [values]);

return (
<View
ref={ref}
style={[
styles.default,
style,
Expand All @@ -81,13 +100,7 @@ const SegmentedControl = ({
nativeEvent: {
layout: {width},
},
}) => {
const newSegmentWidth = values.length ? width / values.length : 0;
if (newSegmentWidth !== segmentWidth) {
animation.setValue(newSegmentWidth * (selectedIndex || 0));
setSegmentWidth(newSegmentWidth);
}
}}>
}) => updateSegmentWidth(width)}>
{!backgroundColor && !tintColor && (
<SegmentsSeparators
values={values.length}
Expand Down

0 comments on commit 593e2eb

Please # to comment.