Width of multiline React-Native Text component won't resize to length of longest line of text on Android

Viewed 601

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.

2 Answers

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.

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>
Related