Search code examples
javascriptreactjsreact-hooksstyled-components

Hide Condition Text in ReactJS


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)}
`;

Solution

  • 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>.