Joon
Joon

Reputation: 9874

How to fit content in a row and prevent overflow in react-native?

I have a tableview row like the below.

<View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
  <Text>{user.fullName}</Text>
  <Button/>
</View>

Above renders so that name sticks to the left and button sticks to the right.

-----------------------------------
 User's Full Name           Button
-----------------------------------

It's all good when user's full name is short enough.

However, when user's name is long. This is how it looks.

-----------------------------------
 User's Very Very Long Full Name         Button
-----------------------------------

Now, the row content overflows the row's width and button goes out of the screen and becomes invisible.

What I want is this.

-----------------------------------
 User's Very Very Long...   Button
-----------------------------------

How do I achieve this with flexbox model?

How do I make the name to grow and fill the available width, but not exceed?

Note that Button can grow or shrink based on the local state.

Also, is there equivalent of text-overflow: ellipsis on react-native?

Upvotes: 9

Views: 11914

Answers (2)

Nelu
Nelu

Reputation: 18680

I had a very similar issue and fixed it by adding this to the view containing the text. Then the ellipsis showed up and the text no longer overflows.

flexShrink: 1

Source

Upvotes: 8

agenthunt
agenthunt

Reputation: 8678

You can set flex:1 on the Text to grow relative to the remaining flex items(Button here). There is no flex set on Button, it will occupy as much space it needs. See numberOfLines docs. You can set it to 1 to make the text ellipsize

<View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
  <Text numberOfLines={1} style={{flex:1}}>{user.fullName}</Text>
  <Button/>
</View>

Upvotes: 20

Related Questions