wecoon
wecoon

Reputation: 165

Moving style based on focused condition out of React Native Navigation tab component

I am struggling to move condition setting colors for icon and text in my bottomTab navigation. Maybe I should not worry about it, but I would like to have all styles in one place and a prettier code in general. Maybe someone could put me in the right direction.

<Tab.Screen
  name="Home"
  component={HomeScreen}
  options={{
    tabBarIcon: ({focused}) => (
      <View style={{...styles.tabView}}>
        <Image
          source={require('./assets/icons/favorite.png')}
          resizeMode="contain"
          style={{
            ...styles.tabIcon,
            tintColor: focused ? '#e32f45' : '#748c94',
          }}
        />
        <Text
          style={{
            ...styles.tabText,
            color: focused ? '#e32f45' : '#748c94',
          }}>
          HOME
        </Text>
      </View>
    ),
  }}
/>

Is there any proper way to move condition from Image and Text, like tintColor: focused ? '#e32f45' : '#748c94' to styles.tabIcon. What are my options here and what are the good practices?

Thank You!

Upvotes: 0

Views: 1049

Answers (1)

dianaqqq
dianaqqq

Reputation: 668

You could write that a little prettier, by making a separate component called TabIcon

interface Props {
  focused: Bool
}

export const TabIcon = (props) => {

  return (
    <View style={{...styles.tabView}}>
        <Image
          source={require('./assets/icons/favorite.png')}
          resizeMode="contain"
          style={{
            ...styles.tabIcon,
            tintColor: props.focused ? '#e32f45' : '#748c94',
          }}
        />
        <Text
          style={{
            ...styles.tabText,
            color: props.focused ? '#e32f45' : '#748c94',
          }}>
          HOME
        </Text>
      </View>
  
  
  )
}

And therefore

<Tab.Screen
  name="Home"
  component={HomeScreen}
  options={{
    tabBarIcon: ({focused}) => <TabIcon focused={focused}/>,
  }}
/>

Upvotes: 1

Related Questions