Sam
Sam

Reputation: 2331

React Native Android: Contain text to inside parent view on a single line

The picture to the left below is currently how the text is being displayed in my React-Native project, but I would like the text to be displayed like the picture on the right(Made in Swift).

There are 3 major differences

  1. The text on the left prints on two lines if the text to print is long enough, on iOS, the end of the word will just cut off, sometimes in the middle of a letter(so you would only see the left side of an A or something.)
  2. The text on the left will sometimes be printed outside the button(letters like p)
  3. The text on the right will replace the middle of the word with ... if the text is too long
    • I would like either this effect, or else have the text size shrink in order to fit the text inside the button

enter image description here enter image description here


This is my Component for these buttons with the text inside

<TouchableOpacity style={styles.button} onPress={onPrs} >
    <Text style={styles.text}>{props.name}</Text>
    {premiumLabel}
</TouchableOpacity>

And this is the styling that I use for them

const styles = StyleSheet.create({
...
    button:{
        backgroundColor: '#37E8E8',
        justifyContent: 'center',
        width:'31%',
        borderRadius: 5
    },
...

Upvotes: 0

Views: 1094

Answers (1)

Dev
Dev

Reputation: 98

You have to use ellipsizeMode prop for Text which defines how text is truncated. For your requirement we have to use ellipsizeMode="middle", which fits the text in the container and the missing text in the middle is indicated by an ellipsis (...).

ellipsizeMode is ideally used with one more prop which is numberOfLines, but this will work even if just the width is specified for the Text, which is not the case in yours. Hence, numberOfLines={1} should also be added.

In order to get the desired effect, you can use this

<TouchableOpacity style={styles.button} onPress={onPrs} >
    <Text style={styles.text} ellipsizeMode="middle" numberOfLines={1}>{props.name}</Text>
    {premiumLabel}
</TouchableOpacity>

Read more about ellipsizeMode

Upvotes: 2

Related Questions