react-nativetextellipsistruncated

How to get a Truncated text value in React Native?


Is there exist some way to get the Truncated text in RN when we use numberOfLines?

For example:

Component

 <Text style={{width: 50}} numberOfLines={3}>
    Some very long text with tons of useful info
 </Text>

Output

 Some
 very
 long...

I want to know what exactly the text is visible to the end-user. Is it possible somehow?

Thanks for any help!

P.S. I tried to use Ref features to get the content but it contains props with the whole text so it didn't help


Solution

  • You can use the onTextLayout prop like this.

    The e.nativeEvent.lines has each line in the text, if you have the text and the number of lines then you can use this array like below and view the texts in each line. This works in Android not sure about web.

    export default function App() {
      
      const text =
        "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
    
      const lines = 3;
    
      return (
        <View style={{ flex: 1 }}>
          <Text
            onTextLayout={(e) => {
              const shownText = e.nativeEvent.lines.slice(0, lines).map((line) => line.text).join('');
              alert(shownText);
              const hidenText = text.substring(shownText.length);
              alert(hidenText);
            }}
            numberOfLines={lines}
            onPress={this.toggleUser}>
            {text}
          </Text>
        </View>
      );
    }