2

I have implemented the show more/show less in reactjs in NEXT.JS using styled-components and ellipsis from polished.js. Good thing, its already adjusting to 3 lines regardless of screen size. My problem is that if the descriptions are few. How can I hide the "Show more"?

Codesandbox is here SEE THIS

const DescriptionText = styled.div`
  font-size: 14px;
  margin-top: 20px;
  margin-bottom: 20px;
  ${({ showMore }) => showMore && ellipsis(undefined, 3)}
`;
Gray Singh
  • 320
  • 1
  • 11
  • Use [this method](https://stackoverflow.com/questions/783899/how-can-i-count-text-lines-inside-an-dom-element-can-i) to count lines, and then simply do a conditional rendering. – Eldar B. Aug 02 '21 at 07:27

1 Answers1

2

You can use conditional rendering to render the <ShowMoreText>. You can get the line count by dividing element's offsetHeight by its lineHeight.

const Description = () => {
  const [isShowMore, setIsShowMore] = useState(true);
  const [lineCount, setLineCount] = useState(0);
  const ref = useRef(null);
  const toggleReadMore = () => setIsShowMore((show) => !show);

  useEffect(() => {
    let descp = ref.current;
    let lc =
      descp.offsetHeight /
      parseInt(getComputedStyle(descp).getPropertyValue("line-height"), 10);
    console.log(lc);
    setLineCount(lc);
  }, []);

  return (
    <MainContainer>
      <TitleText>Description</TitleText>
      <DescriptionText ref={ref} showMore={isShowMore}>
        {text}
      </DescriptionText>
      {lineCount >= 3 ? (
        <ShowMoreText onClick={toggleReadMore}>
          {isShowMore ? "Show more..." : "Show less"}
        </ShowMoreText>
      ) : null}
    </MainContainer>
  );
};

CodeSandbox - https://codesandbox.io/s/show-more-based-on-height-in-react-forked-8wqob?file=/Wrapper.js


Note: You may want to explicitly specify line-height for <DescriptionText>.

TechySharnav
  • 4,869
  • 2
  • 11
  • 29