Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 483
user1310969 Avatar asked May 16 '26 08:05

user1310969


1 Answers

you can use Template literals:

<View key={index} style={[styles.forecastItems, styles[`forecastItems${index}`]]}>
like image 126
Sagiv b.g Avatar answered May 17 '26 20:05

Sagiv b.g