Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React native text component using number of lines

Tags:

Is there a way to determine when the text will be truncated when using number of lines ? Have been searching everywhere and no clear answer. Thank you!

like image 919
H. Wynn Avatar asked Apr 03 '19 05:04

H. Wynn


People also ask

How do you handle long texts in React Native?

just put text in a tag view and text will adapt to property of View. Not really, if you put a text of 22100 chars the whole component goes blank.

How do I truncate text in React Native?

React Native allows you to automatically truncate text that will not fit within its <View> container. In most cases this is enough for the device to truncate the text, automatically adding ellipsis to the end of the string (�) after however many lines of text you have specified (In this case, we only want 1 line).


2 Answers

You can use numberOfLines as a props for <Text /> component. Its depend on the width of your component then calculate the length of the text. This prop is commonly used with ellipsizeMode. Example:

<Text numberOfLines={2} ellipsizeMode='tail'>   Lorem Ipsum is simply dummy text of the printing and typesetting industry. </Text> 
like image 183
namth Avatar answered Sep 18 '22 23:09

namth


This is now possible with the onTextLayout event that includes an array of lines being rendered out. Simply looking at the length you can determine if you are at the limit. 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 = 'Fill in some long text yourself ...';  return (<Text   numberOfLines={NUM_OF_LINES}   onTextLayout={({ nativeEvent: { lines } }) =>     setState({ showMoreButton: lines.length === NUM_OF_LINES })   } >   {SOME_LONG_TEXT_BLOCK} </Text>; 
like image 20
Arno Avatar answered Sep 19 '22 23:09

Arno