rookiecookie
rookiecookie

Reputation: 199

React Native: How to conditionally style an element based on the rest of the attributes in the same object?

I have a list of icons in a modal in my React Native app. Since I need to show the availability of these icons based on the colour, I have put them into an array with a boolean attribute. But what I want to know is how to add a conditional style to the icon element based on the boolean attribute of the same object.

Here is the structure of my array:

    const icons = [
        {
            name: 'ATM',
            bool: false,
            return: 
                <FontAwesome 
                    name='euro'
                    size={25}
                    color={bool ? 'green' : 'grey'}
                />
        }
    ]

I then display the icons in my modal like this:

<View style={{flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'space-evenly'}}>
   {icons.map((obj, index) => {
        return (
            <View style={{justifyContent: 'center', alignItems: 'center', padding: wp('2.0%')}}>
                 <TouchableOpacity>
                     {obj.return}
                 </TouchableOpacity>
                 <Text>{obj.name}</Text>
            </View>
         )
     })}
</View>

I've also tried using

this.bool ? 'green' : 'grey'

which does not work.

Upvotes: 0

Views: 427

Answers (2)

Bisma Azher
Bisma Azher

Reputation: 749

Hope so this will help you

const icons = [
        {
            name: 'ATM',
            bool: false,
            return: 
                <FontAwesome 
                    name='euro'
                    size={25}
                    color={this.bool == true ? 'green' : 'grey'}
                />
        }
    ]

Upvotes: 0

Krismu
Krismu

Reputation: 503

I don't think there's a way to access the value of bool from within.

You can try setting the right style when initializing the array but I'd recommend not to store react Elements directly in large arrays for performance reasons and instead display icons in your modal like this:

<View style={{flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'space-evenly'}}>
   {icons.map((obj, index) => {
        return (
            <View style={{justifyContent: 'center', alignItems: 'center', padding: wp('2.0%')}}>
                 <TouchableOpacity>
                     <FontAwesome 
                    name='euro'
                    size={25}
                    color={obj.bool ? 'green' : 'grey'}
                />
                 </TouchableOpacity>
                 <Text>{obj.name}</Text>
            </View>
         )
     })}
</View>

Upvotes: 1

Related Questions