Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 20 additions & 7 deletions js/SegmentedControl.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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;
Expand All @@ -66,8 +78,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 @@ -79,13 +98,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