Home > Software design >  How to have different style for items at certain locations in a Flatlist in React Native?
How to have different style for items at certain locations in a Flatlist in React Native?

Time:10-26

I'm trying to have different styles for the last item in a list, as shown in the picture below:

enter image description here

Is there any way to pass the location of an item in the list to the item itself so it can be applied to a different style? Or there are other better approaches?

here is my code

 <Box flex="1">
        <MainHeader />
        <View>
          <FlatList
            numColumns={2}
            data={Index_List}
            contentContainerStyle={{
              alignItems: "center",
              justifyContent: "space-between",

            }}
            keyExtractor={(item, index) => index.toString()}
            renderItem={({ item }) => {
              return (
                <Box m='4'>
                  <TextComp title={item.title} img={item.img} />
                </Box>
              )
            }}
          />
        
        </View>

      </Box>

I have tried to use nested flat list but it did not work

CodePudding user response:

You can change the style of the flatlist button by the index approach. renderItem() offers props item, index and separator. You can find it here.

<FlatList
  numColumns={2}
  data={Index_List}
  contentContainerStyle={{
    alignItems: "center",
    justifyContent: "space-between",
  }}
  keyExtractor={(item, index) => index.toString()}
  renderItem={({ item, index }) => {  //<- Add index props here
    if(index == Index_List.length-1){
      //If last item
      return(<View>...</View>);
    }

    return (
      <Box m='4'>
        <TextComp title={item.title} img={item.img} />
      </Box>
    )
  }}
/>

CodePudding user response:

Have you tried targeting the last item via the index.

renderItem={({ item, index }) => (
          <Box
            style={{
              width: INDICATOR_WIDTH,
              height: INDICATOR_WIDTH * 0.8,
              borderColor: index === data.length - 1 ? "#fff" : "transparent",
            }}
            
          ></Box>
       
      )}

Or

renderItem={({ item, index }) => (
      <Box
        style={ i === data.length - 1 ? {
          width: INDICATOR_WIDTH,
          height: INDICATOR_WIDTH * 0.8,
          
        }: {}}

      ></Box>

  )}
  • Related