Skip to content

Does not behave as a controlled component on iOS #753

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
madox2 opened this issue Jul 11, 2023 · 1 comment
Open

Does not behave as a controlled component on iOS #753

madox2 opened this issue Jul 11, 2023 · 1 comment

Comments

@madox2
Copy link

madox2 commented Jul 11, 2023

I am trying to use segmented control as a controlled component through selectedIndex and onChange properties. On iOS it does not work as expected. In the simple example below I want to execute special logic when clicking 'More' item, but it is ignoring the value prop and keeps selecting 'More' item.

export function Navigation() {
  const [value, onChange] = useState(0);
  return (
    <SegmentedControl
      values={['One', 'Two', 'More']}
      selectedIndex={value}
      onChange={event => {
        const { selectedSegmentIndex } = event.nativeEvent;
        if (selectedSegmentIndex > 1) {
          // onChange(value); // does not work either
          return;
        }
        onChange(selectedSegmentIndex);
      }}
    />
  );
}

On Android it works as expected.
Version: "@react-native-segmented-control/segmented-control": "^2.4.2"

@VNDRN
Copy link

VNDRN commented Nov 14, 2024

Hi there,
Just had a similar issue in our codebase where we wanted to prevent/revert the switching to a tab in onChange.
I adjusted our implementation for your useCase. It won't prevent setting more as the active element (as that's done natively on iOS), but it'll immediately update it to the segment index you provide:

export default function Navigation() {
  const [value, onChange] = useState(0);

  return (
    <SegmentedControl
      values={['One', 'Two', 'More']}
      selectedIndex={value}
      onChange={({nativeEvent}) => {       
        // align our state with the internal state of the segmented control
        onChange(nativeEvent.selectedSegmentIndex);
        
        if (nativeEvent.selectedSegmentIndex > 1) {
          // when 'more' is active, set it back to 'Two"
          InteractionManager.runAfterInteractions(() => {
            onChange(1);
          });
        }
      }}
    />
  );
}

If you want it to revert to the tab that was initially selected, I'd keep hold of that tab in a ref.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants