I just figured out how to solve this for React.
As Khodor mentioned, line-clamp is what you want. However, it's not currently supported by the official CSS spec. So, you can use -webkit-line-clamp as a sort of workaround. However, I struggled to figure out the exact syntax needed for React. I eventually figured out it out by peeking at the source code for this NPM package react-lines-ellipses and searching for 'webkit' in his github repo.
The React-specific CSS
const textStyle = {
maxWidth: '100%',
display: '-webkit-box',
WebkitBoxOrient: 'vertical',
WebkitLineClamp: 3,
overflow: 'hidden',
textOverflow: 'ellipsis',
};
I set the maxWidth
to ensure the text filled the whole width of the display element. This is optional.
overflow: 'hidden'
hides the extra text beyond the 3 lines (I chose 3 at random).
textOverflow: 'ellipses'
adds an ellipses (...) to the end of the line, where it gets cut off.
The JSX
<div
onClick={toggleTruncate}
style={calculateTextStyle()}
>
This is where my long text goes.
</div>
// This function returns the correct style to the above div.
function calculateTextStyle() {
return truncate ? textStyle : null;
}
// I used React Hooks to create a variable in state to manage if the text should be truncated or not.
const [truncate, setToggleTruncate] = React.useState(true);
// This function toggles the state variable 'truncate', thereby expanding and truncating the text every time the user clicks the div.
function toggleTruncate() {
setToggleTruncate(!truncate);
}