react-nativewix-react-native-navigation

How to change rightButton image dynamically?


I need to change an icon for a topBar's rightButton once it's pressed, and use it as a toggle, to show items on a map or a grid. The problem is that my screen component options are static, and can't find a way to re-render my screen. I've seen that there's a way to pass props to the static options, but still, can't re-render my screen to set a different icon once the button is pressed. Any ideas on how to solve this? Thank you!

My Code:

const ResultsScreen = ({ componentId }) => {
  const [isMapActive, setIsMapActive] = useState(false);
  const [items, setItems] = useState([]);

  useNavigationButtonPress((event) => {
    if(event.buttonId == 'toggleMapGrid') {
      setIsMapActive(!isMapActive);
    }
  });

  const ResultsSection = isMapActive ? (
    // TODO: Temporary no-map
    <View style={{ backgroundColor: 'red', flex: 1 }} />
  ) : (
    <ItemsGrid parentComponentId={componentId} items={items} />
  );

  return (
    <SafeAreaView style={styles.container}>
      <FilterList style={styles.filters} />
      {ResultsSection}
    </SafeAreaView>
  );
};

ResultsScreen.options = () => ({
  topBar: {
    animate: true,
    rightButtons: [
      {
        id: 'toggleMapGrid',
        icon: R.images.location24, // or R.images.map24, depending on isMapActive
      },
    ],
  },
});

How the right button should change each time I tap.


Solution

  • After some time, I solved this issue using mergeOptions API

    const ResultsScreen = () => {
    ...
      const [isMapActive, setIsMapActive] = useState(false);
    
      Navigation.mergeOptions(componentId, {
        topBar: {
          rightButtons: [
            {
              id: 'advancedFilters',
              icon: R.images.filter24,
            },
            {
              id: 'toggleMapGrid',
              icon: isMapActive ? R.images.list24 : R.images.location24,
            },
          ],
        },
      });
      }
    ...