0

How could I check how many lines a rendered text takes, no matter if it's displayed on a large or small screen?

On the below component I want to show the anchor element only if the text has 3 lines.

import React from 'react';

type contentProps = {
  content: string,
};

function subString(string: string): string {
  return string.substring(0, string.length / 2);
}

export const Content = ({ content }: contentProps) =>
  content ? (
    <p className="content">
      {subString(content)}
      <a href="#">See More</a>
    </p>
  ) : null;

What should be the flow ? First i need to render the component Second check if it takes 3 lines and after this change the state ?

  • Does this answer your question? [How can I count text lines inside an DOM element? Can I?](https://stackoverflow.com/questions/783899/how-can-i-count-text-lines-inside-an-dom-element-can-i) – julianobrasil May 06 '20 at 09:04
  • @MarcosMolina Exactly, you need to render it first and then check its length there, no way to safely tell beforehand. If you knew the size, font, letter spacing and all the other stuff you could use canvas for that, but as long as you are not sure, this is the approach. – Akxe May 06 '20 at 10:49
  • So the content should be a prop or a state ? also the button See more than after click I show all the string and changes to see less? – Marcos Molina May 06 '20 at 11:59

0 Answers0