fmoga
fmoga

Reputation: 233

React Native handling ellipsis when multiple Text components in a row

I am trying to build a comments section in React Native but I'm having trouble handling text overflow and ellipsis properly.

The structure is simple and looks as follows: enter image description here

Ideally, when the username is long enough it should be trimmed and the action name should be pushed all the way to the right until it reaches the timestamp like this:

enter image description here

The closest I got was using this code:

const styles = StyleSheet.create({
    commentRow: {
        padding: 10
    },
    commentTopRow: {
        flexDirection: 'row',
        alignItems: 'center'
    },
    commentTitle: {
        flex: 1
    },
    author: {
        fontWeight: '500'
    },
    commentBody: {
        paddingTop: 5,
        paddingBottom: 5
    }
});

<View style={styles.commentRow}>
    <View style={styles.commentTopRow}>
        <Text style={styles.commentTitle} numberOfLines={1}>
            <Text style={styles.author}>User Name</Text>
            <Text style={styles.action}> commented</Text>
        </Text>
        <Text style={styles.timestamp}>8h</Text>
    </View>
    <Text style={styles.commentBody}>comment body</Text>
</View>

which yields the following results:

enter image description here enter image description here

Any help in figuring out a unique structure and style set that will handle both cases would be greatly appreciated.

Thanks!

Upvotes: 7

Views: 6077

Answers (2)

JChen___
JChen___

Reputation: 3701

This gonna be work

 <View style={styles.commentRow}>
     <View style={styles.commentTopRow}>
         <View style={styles.commentTitle}>
             <Text numberOfLines={1}>
                 <Text style={styles.author}>User Name</Text>
                 <Text style={styles.action}> commented</Text>
             </Text>
         </View>
         <View>
            <Text style={styles.timestamp}>8h</Text>
         </View>
     </View>
     <Text style={styles.commentBody}>comment body</Text>
 </View>

In a word, you should use The View to layout, not the Text

Upvotes: -1

RandyTek
RandyTek

Reputation: 4744

According to Facebook's guide,

In React Native flex does not work the same way that it does in CSS. flex is a number rather than a string, and it works according to the css-layout library at https://github.com/facebook/css-layout.

When flex is -1, the component is normally sized according width and height. However, if there's not enough space, the component will shrink to its minWidth and minHeight.

So basically you need to set the correct flex values for your components. I suppose you do not want commented and 8h to shrink. Then, you need to set flex values to 0 for these components to make them inflexible to shrink. And set 0 to long long user name to make it flexible to shrink when space is not enough.

Upvotes: 6

Related Questions