How to determine number of lines of Text component with React Native?

Sometimes, we want to determine number of lines of Text component with React Native.

In this article, we’ll look at how to determine number of lines of Text component with React Native.

How to determine number of lines of Text component with React Native?

To determine number of lines of Text component 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() {
  const [showMore, setShowMore] = React.useState(false);
  const onTextLayout = React.useCallback((e) => {
    setShowMore(e.nativeEvent.lines.length > NUM_OF_LINES);
  }, []);

  return (
    <Text numberOfLines={NUM_OF_LINES} onTextLayout={onTextLayout}>
      {SOME_LONG_TEXT_BLOCK}
    </Text>
  );
}

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

Then we set the onTextLayout prop to the onTextLayout function and get the number of lines displayed with e.nativeEvent.lines.length .

And if e.nativeEvent.lines.length is bigger than NUM_OF_LINES.

We call setShowMore to set showMore to true.

Conclusion

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