Home > Blockchain >  How we detect no of lines of text component in react native?
How we detect no of lines of text component in react native?

Time:07-30

How we detect no of lines of the text component in react native to help in see more option, I worked OnTextLayout prop of text but it does not work. Any solution?

CodePudding user response:

You should always share the code that you've worked on even if it doesn't work. So the community can guide to the right direction. Having said that this is tested code and it should work try this.

const onLayout = (e) => {
  console.log(e.nativeEvent.lines.length)
},

<Text onTextLayout={onLayout}>Hello</Text>

CodePudding user response:

checkout this approach with using useCallback, this is optimum solution of my knowledge, showMore is the state for show show more option

const NUM_OF_LINES = 5;
const dummyLongText = 'Lorem ipsum ...';

function SomeComponent () { 
  const [ showMore, setShowMore ] = useState(false);
  const onTextLayout = useCallback(e => {
    setShowMore(e.nativeEvent.lines.length >= NUM_OF_LINES);
  }, []);

  return (
    <Text numberOfLines={noOfLines} onTextLayout={onTextLayout}>
      {dummyLongText}
    </Text>
  );
}
  • Related