I am trying to find a way to have show more/less text if there are more than 3 lines of text. I have tried the react-show-more-text package but it was very buggy so the closest I have been able to get is the top answer in this post. The main issue is that if there are only 3 lines its showing the read more/less text also. It should be show if there would actually be another line of text when you hit the button. My code.
import React, { useCallback, useState } from 'react';
import { Text } from 'react-native';
const ReadMoreText = ({ readMoreStyle, text, textStyle }) => {
const [textShown, setTextShown] = useState(false);
const [lengthMore, setLengthMore] = useState(false);
const toggleNumberOfLines = () => {
setTextShown(!textShown);
};
const onTextLayout = useCallback((e) => {
setLengthMore(e.nativeEvent.lines.length >= 3);
}, []);
return (
<>
<Text onTextLayout={onTextLayout} numberOfLines={textShown ? undefined : 3} style={textStyle}>
{text}
</Text>
{lengthMore ? (
<Text onPress={toggleNumberOfLines} style={readMoreStyle}>
{textShown ? 'Read Less' : 'Read More'}
</Text>
) : null}
</>
);
};
export default ReadMoreText;