user1310969
user1310969

Reputation: 201

Index in style property with react native

I'm building an app with react native and i try to pass an index to a style property, to have different backgroundColor.

here's my code :

getData(data){
    const items = data.map((item, index) =>
        <View key={index} style={[styles.forecastItems, styles.forecastItems0]}>
            <Text>{item.day}</Text>
            <Image source={item.url}/>
            <Text>{item.temp}</Text>
        </View>
    );
    return (items)
}

in styles.forecastItem0 i want to have the index instead of 0. i don't find a solution. Thanks for your help

Upvotes: 3

Views: 402

Answers (3)

Code-Apprentice
Code-Apprentice

Reputation: 83557

You should create forecastItems as an array:

styles = {
    forcastItems = [1, 2, 3, 4]
}

Now you can index the array in a straightforward manner:

<View key={index} style={[styles.forecastItems, styles.forecastItems[index]]}>

Note that you should always use an array instead of creating variable names (or keys in an object) which differ only with a number suffix.

Upvotes: 0

Ali Faris
Ali Faris

Reputation: 18610

you can access properties of style object by using brackets like this

<View key={index} 
      style={[styles.forecastItems, styles.["forecastItems" + index] ]}
>

Upvotes: 0

Sagiv b.g
Sagiv b.g

Reputation: 31024

you can use Template literals:

<View key={index} style={[styles.forecastItems, styles[`forecastItems${index}`]]}>

Upvotes: 1

Related Questions