Search code examples
react-nativereact-native-listview

Listview with alternating color in react native


I have array of objects like the example below;

[{
        "id" : 13100,
        "key" : "Emlak Vergisi",
        "y" : 135638.98
    }, {
        "id" : 13154,
        "key" : "Çevre Temizlik ",
        "y" : 956.17
    }, {
        "id" : 19998,
        "key" : "Genel Tahakkuk",
        "y" : 89030.62
    }, {
        "id" : 24998,
        "key" : "Gecekondu ve So",
        "y" : 42721.07
    }, {
        "id" : 60000,
        "key" : "Ortak Gelirler",
        "y" : 827.42
    }
]

Is it possible to have a listview with alternating color for each item?


Solution

  • I would say this approach is cleaner:

     renderRow(rowData, sectionID, rowID) {
    
       let style = [
             styles.row, 
             {'backgroundColor': colors[rowID % colors.length]}
           ];
    
       return (<View style={style}/>);
     }
    
     let colors = ['#123456', '#654321', '#fdecba', '#abcdef'];
    
     let styles = StyleSheet.create({
           row: {
                // .. rows style
           }
     });
    

    This way you can easily add a specail color to each row in the list (not only by even/odd type)