How to truncate text component using number of lines with React Native?

Sometimes, we want to truncate text component using number of lines with React Native.

In this article, we’ll look at how to truncate text component using number of lines with React Native.

How to truncate text component using number of lines with React Native?

To truncate text component using number of lines with React Native, we can get it from the onTextLayout callback’s parameter.

For instance, we write:

import * as React from 'react';
import { View, Animated, ScrollView, Text } from 'react-native';
import Constants from 'expo-constants';
import { Card } from 'react-native-paper';

const NUM_OF_LINES = 3;
const SOME_LONG_TEXT_BLOCK =
  'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque pulvinar sem at leo dapibus maximus. Pellentesque nec scelerisque ipsum. Vestibulum sit amet orci vel augue suscipit maximus. Morbi malesuada augue eu sapien iaculis laoreet. Nunc augue purus, ultricies at auctor non, dapibus a ligula. Integer rutrum congue erat a rutrum. ';

export default function App() {
  return (
    <Text numberOfLines={NUM_OF_LINES} ellipsizeMode="tail">
      {SOME_LONG_TEXT_BLOCK}
    </Text>
  );
}

to set numberOfLines to NUM_OF_LINES to restrict the number of lines to display.

We set ellipsizeMode to 'tail' to add the ellipsis after the truncated text.

Conclusion

To determine number of lines of Text component with React Native, we can get it from the onTextLayout callback’s parameter.