quirky purple
quirky purple

Reputation: 2219

Ellipsize text that is between two other texts without flexing trailing text to end

I have a view that has flexDirection: 'row' that will contain 3 text elements. I want the text elements to flow one after the other, but in the case that space is limited, I want the middle text element to be the one that is ellipsized.

Ex. where | is the edge of the screen

| John Smith [email protected] 9/24/19 |

but if the device is small

| John Smith johnsmith@t.. 9/24/19 |

A solution related to a different question suggested putting the middle text inside a view with flex: 1, which does cause the middle text to be the ellipsized text (when I also indicate the numberOfLines and ellipsizeMode properties) but that causes the trailing text to be pushed to the end, like the following

| John Smith [email protected] 9/24/19|

which I don't want.

Here is a snack with the code

https://snack.expo.io/Sk6_MldDH

Or here is an example component

export default class App extends React.Component {
  render() {
    return (
      <View style={{ flex: 1 }}>
      // If space is tight, I want the middle text ellipsized 

      <View style={{flexDirection: 'row', width: 250, borderWidth: 1}}>
       <Text>John Smith</Text>
       <View style={{flex: 1}}>
       <Text ellipsizeMode="tail" numberOfLines={1} style={{ color: 'gray', marginHorizontal: 8}}>[email protected]</Text>
       </View>
       <Text style={{ color: 'gray'}}>9/24/19</Text>
       </View>

      // If plenty of space, I want the date to immediately follow the email, not have it pushed to the end

      <View style={{flexDirection: 'row', width: 350, borderWidth: 1}}>
       <Text>John Smith</Text>
       <View style={{flex: 1}}>
       <Text ellipsizeMode="tail" numberOfLines={1} style={{ color: 'gray', marginHorizontal: 8}}>[email protected]</Text>
       </View>
       <Text style={{ color: 'gray'}}>9/24/19</Text>
       </View>
      </View>
    );
  }
}

Upvotes: 1

Views: 67

Answers (1)

Zaytri
Zaytri

Reputation: 2574

Here's a snack with my solution: https://snack.expo.io/rkEncIYvS

Within the View:

<Text ellipsizeMode='tail' numberOfLines={1}>John Smith <Text style={{ color: 'gray', marginHorizontal: 8}}>[email protected]</Text></Text>
<Text style={{ color: 'gray', flex: 1}}>9/24/19</Text>

I could not find a way to keep the name and email separate without the name overflowing into the next line.

However, with nested Text components, you can achieve a similar result.

Setting flex: 1 on the date ensures that the date Text component will attempt to fill the remaining space.

Upvotes: 1

Related Questions