If you're using styled-components
, there's a fantastic utility package that I recommend checking out: polished.js
The specific utility you may be interested in is the ellipsis function.
ellipsis
This CSS feature allows for truncated text with an ellipsis. You have the option to specify a max-width and number of lines before truncation.
ellipsis(width: (string? | number?)?, lines: number): Styles
For example, you can display up to 3 lines when showing more information; otherwise, show the full text.
import { ellipsis } from 'polished';
...
const DescriptionText = styled.div`
font-size: 14px;
margin-top: 20px;
margin-bottom: 20px;
${({ showMore }) => showMore && ellipsis(undefined, 3)}
`;
...
const Description = () => {
const [isShowMore, setIsShowMore] = useState(true);
const toggleReadMore = () => setIsShowMore(show => !show);
return (
<MainContainer>
<TitleText>Description</TitleText>
<DescriptionText showMore={isShowMore}>{text}</DescriptionText>
<ShowMoreText onClick={toggleReadMore}>
{isShowMore ? "Show more..." : "Show less"}
</ShowMoreText>
</MainContainer>
);
};
https://i.sstatic.net/1cKwn.png https://i.sstatic.net/9UUx2.png
https://codesandbox.io/s/show-more-based-on-height-in-react-5r25s?fontsize=14&hidenavigation=1&module=%2FWrapper.js&theme=dark
In a previous response, you mentioned avoiding new dependencies. The CSS applied through the ellipsis
utility could be a solution for you. However, integrating polished
into your project is highly recommended due to its array of useful styling utilities.
import styled, { css } from "styled-components";
const DescriptionText = styled.div`
font-size: 14px;
margin-top: 20px;
margin-bottom: 20px;
${({ showMore }) =>
showMore &&
css`
display: -webkit-box;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: normal;
word-wrap: normal;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;
`}
`;
To cater to various screen sizes and responsiveness, utilize media queries to specify different initial line displays.