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