Edit: THIS NO LONGER WORKS in newer versions of react-native, I’m aware of that.
It once worked but the nativeEvent no longer returns the number of lines. I’m leaving this here as someone might be on an older version of react-native.
—
I want to provide a modern solution. There is now a onTextLayout
event that includes an array of lines
which can be determined what number of lines are being rendered. There’s other details in the lines
array like actual height and width of every line which can be further used to determine if the text is being truncated.
const NUM_OF_LINES = 5;
const SOME_LONG_TEXT_BLOCK = 'Lorem ipsum ...';
function SomeComponent () {
const [ showMore, setShowMore ] = useState(false);
const onTextLayout = useCallback(e => {
setShowMore(e.nativeEvent.lines.length > NUM_OF_LINES);
}, []);
return (
<Text numberOfLines={NUM_OF_LINES} onTextLayout={onTextLayout}>
{SOME_LONG_TEXT_BLOCK}
</Text>
);
}