Reputation: 201
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
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
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
Reputation: 31024
you can use Template literals:
<View key={index} style={[styles.forecastItems, styles[`forecastItems${index}`]]}>
Upvotes: 1