6

I have a text component which is contained within a parent of a set width alongside a small black box to its right. My question is why does the text elipsise only when it reaches the end of the parent container when the black box (its sibling) is pushed out? How can I make the text respect the space of its sibling and elipsise earlier?

<View style={{height: 30, width: 200, flexDirection: "row", borderWidth: 1}}>
    <Text numberOfLines={1}>
        {"This is a very very very long sentence that is meant to elipsize"}
    </Text>
    <View style={{width: 20, height: 20, backgroundColor: "black"}} />
</View>

This is what this result looks like

enter image description here

2 Answers 2

6

Just you need to wrap the Text component into a View with { flex: 1 } style. It should help:

<View style={{height: 30, width: 200, flexDirection: "row", borderWidth: 1}}>
  <View style={{flex: 1}}>
    <Text numberOfLines={1}>
      {"This is a very very very long sentence that is meant to elipsize"}
    </Text>
  </View>
  <View style={{width: 20, height: 20, backgroundColor: "black"}} />
Sign up to request clarification or add additional context in comments.

3 Comments

It work !, but why does the flex: 1 made this magic ?
@user2877989 maybe, because flex means expand child component within parent component explicitly?
this was a life saver!
3

In React Native, a Text component does not behave according to the box model. So it shrinks and expands according to its need, given the dimensions of the parent component (and sometimes overflowing it depending on the styling).

An easy fix in such case is to wrap the Text component in its own view. Setting the Text component width will also work.

4 Comments

Thank you for the reply. My issue is however, that I'd like the text to resize based on how much space the box to the right takes up. So rather than setting a value for the width of the Text, I'd like to give a width to the box and have the text change based on how much space the box gives it.
Yes, so my first suggestion apply: You wrap the text field in a View container. This way it will behave like a box in the context of the flex and resize the way you expect
Unfortunately it is behaving in the same way when I wrap the text field in a view. Is there a specific styling you would recommend for the view? Feel free to try the example code if you want I think it should run. Cheers!
The view that wraps the two components should be explicitly using flex AND the children components must not have a fixed width. This way the flex algo will determine the space taken for each component

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.