0

I'm working on an app with React Native.

I have a "Card" component that display Text elements, which can have any amount of characters.

So right now I'm trying to set a dynamic height for my card. My idea is to set a certain height if the amount of lines is 1, a larger height if the amount of lines is 2, and a larger one if it's 3 or more (truncating the text with ellipsis).

Is there any way I can get the amount of lines the takes, so I can determine which height I should use?

An option would be to do it based on the amount of characters, but that wouldn't work properly in different sized devices.

I feel this is something easy and there's a common way to do it, but I can't seem to realize how to implement it.

Thanks!

Franco Muñiz
  • 811
  • 1
  • 10
  • 21
  • 1
    Does this answer your question? [How to get the current number of lines in String of TextInput?](https://stackoverflow.com/questions/56663069/how-to-get-the-current-number-of-lines-in-string-of-textinput) – Tim Jun 24 '20 at 06:56
  • I've already answered your question here: https://stackoverflow.com/questions/56663069/how-to-get-the-current-number-of-lines-in-string-of-textinput/56663717#56663717 – Tim Jun 24 '20 at 06:56

2 Answers2

4

One immediate solution is to get the compiled height of text input and divide it by line height you have set in styles.

<Text onLayout={(event) => {
  const {height} = event.nativeEvent.layout;
  const lineHeight = 14;
  console.log('my text has'+ height/lineHeight +' lines')
}} />
  • While this code may resolve the OP's issue, it is best to include an explanation as to how your code addresses the OP's issue. In this way, future visitors can learn from your post, and apply it to their own code. SO is not a coding service, but a resource for knowledge. Also, high quality, complete answers are more likely to be upvoted. These features, along with the requirement that all posts are self-contained, are some of the strengths of SO as a platform, that differentiates it from forums. You can edit to add additional info &/or to supplement your explanations with source documentation. – ysf Jun 24 '20 at 08:17
  • Understood. Short description added. – Dmitriy Godlevski Jun 24 '20 at 12:17
1

this is my solution. it work perfect on android

  const [textLength, setTextLength] = useState(0);
  const onTextLayout = useCallback(e => {
    setTextLength(e.nativeEvent.lines.length);
  }, []);

  return (
    <Text onTextLayout={onTextLayout}>
      {SOME_TEXT_BLOCK}
    </Text>
  );
donkey
  • 478
  • 7
  • 10