3

I have a multiline React-Native Text component whose width should auto-adjust to the width of the longest line of text. This is working on iOS but not on Android, and I'm not sure why.

Please see this expo snack for a demo. on iOS it looks like this:

enter image description here

on Android it looks like this:

enter image description here

The demo above is just a stripped down excerpt from the full app. I need to keep flexDirection: 'row' because in the full app there are other items I need to display to the right of this textbox.

JMLdev
  • 846
  • 2
  • 10
  • 21
  • In your text resource, do you have a line break after 'Indubitably.'? What exactly do you mean by 'width of the longest line of text.'? – nulldroid Aug 14 '20 at 17:24
  • 1
    No line breaks in that string at all. By "width of the longest line of text" I mean that the text box should be no longer than the end of "Indubitably." - basically no wider than it needs to be to encapsulate all of the text. – JMLdev Aug 17 '20 at 16:42

2 Answers2

0

Instead of useState, try using a string variable with a linebreak:

const TextInANest = () => {
  var bodyText = "This is not really a bird nest. Nope. Indubitably.\n Antagonistic."
   // const bodyText = useState("This is not really a bird nest. Nope. Indubitably. Antagonistic.");

This way, you will get the same result on Android and iOS. It's more like a workaround than a solution but hope its helpful, still.

nulldroid
  • 1,150
  • 8
  • 15
  • Unfortunately I have a lot of these text boxes and the text strings are variable so I can't manually line break every single one of them. – JMLdev Aug 17 '20 at 16:43
0

I searched for the same but didn't find anything. I tried some "flex" solutions but it didn't work. Finally I've written "react" solution and it works (TypeScript):

const [maxLineWidth, setMaxLineWidth] = useState<number>()
const onTextLayout = useCallback((event: NativeSyntheticEvent<TextLayoutEventData>) => {
    const nextMaxLineWidth = event.nativeEvent.lines.reduce((result, line) => Math.max(result, line.width), 0)
    setMaxLineWidth(Math.ceil(nextMaxLineWidth))
}, [])
// ...
<Text
    style={{ width: maxLineWidth }}
    onTextLayout={onTextLayout}
>
    Very very long text!!!
</Text>
Dem0n13
  • 766
  • 1
  • 13
  • 37