Add image instead of string title to react-native-segmented-control-tab

Viewed 461

I'm using react-native-segmented-control-tab in my project and it works fine. Below is my current code

<SegmentedControlTab
                tabsContainerStyle={styles.tabsContainerStyle}
                tabStyle={styles.tabStyle}
                activeTabStyle={styles.activeTabStyle}
                values={["First", "Second", "Third"]}
                selectedIndex={this.state.selectedIndex}
                onTabPress={this.handleIndexChange}
              />

This displays segment with title string "First, Second and Third". Now instead of these strings, I would like to replace them with images. Is that possible? How do I go about it?

1 Answers

I found a way to do this (only works on Android...) by looking into the source code of the @react-native-community/segmented-control library (version '^2.2.1') - file 'SegmentedControlTab.js' line 84.

<TouchableOpacity
  style={styles.container}
  disabled={!enabled}
  onPress={onSelect}>
  <View style={[styles.default]}>
    {typeof value === 'number' || typeof value === 'object' ? (
      <Image source={value} style={styles.segmentImage} />
    ) : isBase64(value) ? (
      <Image source={{uri: value}} style={styles.segmentImage} />
    ) : (
      <Text style={[idleStyle, selected && activeStyle]}>{value}</Text>
    )}
  </View>
</TouchableOpacity>

This is the code that renders each of the text values passed in. As you can see, if you pass in a number or an object (such as {uri: 'https://icons.iconarchive.com/icons/papirus-team/papirus-apps/256/albion-online-icon.png'}) the library will render an <Image /> element. You can also send a Base64 encoded image, and it will render an <Image />.

If you pass in something that is neither a number, object nor a Base64 string, the library renders a <Text> element.

Example below:

    <SegmentedControl
      values={['data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAA7klEQVQ4T92Uvw6CQAzGvzPRxNXkNOCiz8Do5Is7uvEIhkkwnnF00AFTkpJayh8TJlg40q8fv7Z35zDy40b2w8QM95EvZYuyIjQqNEvmRCuBDLvinYZ9A/uH8AVg2WZIRkQ5c+5wye9nqasJkwTzZ+7fHCyBqwO2kkKWuov9yZU4kn4Vh0Wa4kPrylA3W5GFrAhr1jGdRU+xCp2CTELfnKTfrNMaCVUZSjOZpCkknV6zqWnYVo61ZTRQo2Q2k0L9AyvGrfsZilW6RWv1nVtVbxs16UdWBN+1sfeRvwHYsIZhJnbb9J3t+qQMEQ7VfAGjuKJN2bFKJQAAAABJRU5ErkJggg==', {uri: 'https://icons.iconarchive.com/icons/papirus-team/papirus-apps/256/albion-online-icon.png'}]}
      style={segmentControlStyles.container}
      selectedIndex={accessByIndex}
      onChange={onAccessByChange}
      backgroundColor={mainColors.segmentBackground}
      fontStyle={segmentControlStyles.text}
    />

Result:

Segmented control with images - example

P.S. This solution works on Android only... I haven't found a way to make it work on iOS.

Related