React Native: Determine number of lines of Text component React Native: Determine number of lines of Text component ios ios

React Native: Determine number of lines of Text component


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>  );}


It looks like React Native 0.24 implements an onLayout function
http://facebook.github.io/react-native/docs/text.html#onlayout

onLayout function
Invoked on mount and layout changes with
{nativeEvent: {layout: {x, y, width, height}}}

So it looks like you could pass an onLayout callback function, get the height of the Text component and then do some calculations using the line height to get to the number of lines


This one is working for both IOS AND Android

    const [ loadMore, setLoadMore ] = useState(false);    const [ numOfLines, setNumOfLines ] = useState(0);    const onTextLayout = useCallback(e => {        if(numOfLines == 0)            setNumOfLines(e.nativeEvent.lines.length);    });    const onLoadMoreToggle = () => {        setLoadMore(!loadMore);    }        return (        <View style={styles.container}>            <Text                 numberOfLines={numOfLines == 0 ? null : loadMore ? numOfLines : NUM_OF_LINES}                 onTextLayout={onTextLayout}                 style={styles.bodyText}            >                {props.children}            </Text>            {                (numOfLines > NUM_OF_LINES) &&                <View style={styles.linkContainer}>                    <TouchableRipple onPress={onLoadMoreToggle}>                        <Text style={styles.linkText}>{ loadMore? 'Load Less' :'Load More'}</Text>                    </TouchableRipple>                </View>            }        </View>    )const styles = StyleSheet.create({    container: {        display: 'flex',        flexDirection:'column',    },    bodyText: {        flex:1,    },    linkContainer: {        flexDirection: 'row',        justifyContent: 'flex-end'    },      linkText: {        color: '#2196f3'    }})


matomo