Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native flexbox - detect last element in row

I have a dynamic list with text (tags, for example) rendered in a row with flex-wrap. I want to add a bullet separator between all items, except for every last one in each row.

For example, let's say I have the list ['apple', 'peach', 'orange', 'watermelon', 'pear']. Depending on screen size, I want them rendered in rows and little bullets between.

apple • peach • orange

watermelon • pear

As you can see, there would be two rows and bullets only between element on one row. Now, I can use index to check whether it is the last element in the list arr.map((i, index) => index < arr.length-1 && <View>...</View>) but I get a bullet after the last element in the first row

apple • peach • orange •

watermelon • pear

and that is not what I want. Now let's say I have longer names of the items and only two of them are rendered in the first row, I want the same effect, no bullets at the end.

Can someone help me to detect the last element in one row.

Here is example of my code.

<View style={styles.section}>
    {
        tags.map((tag, index) => (
            <View key={tag.id} style={styles.tagItem}>
                <Text style={styles.tagTitle}>{tag.title}</Text>
                {index < tags.length - 1 && <Text>•</Text>}
            </View>
        ))
    }
</View>

And this is my styles object:

{
    section: {
        flexDirection: 'row',
        flexWrap: 'wrap',
    },
    tagItem: {
        paddingHorizontal: 5,
        flexDirection: 'row',
    },
}
like image 911
Ilcho Taleski Avatar asked Sep 22 '26 01:09

Ilcho Taleski


1 Answers

You can divide them in sets by the offset on y-axis. Then you can check which element is furthest to the right from each set and then you can skip that dot.

like image 197
n.pejovski Avatar answered Sep 23 '26 14:09

n.pejovski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!