-2

I have created a card in Material UI containing text. I'd like to fix the height of the card and have the text within it truncate if it goes beyond 3 lines. What's the best way to do this?

Below is my code where, as you can see, I have tried to use CSS to do this, but (a) the ellipses doesn't show (b) the overflow chops off the text on the horizontal so I'd like to have a way to do it by multiples of the line height rather than by pixels. I'd also like it to still work if the monitor size adjusts.

import React from 'react';

// Material UI
import {
  Card,
  CardActionArea,
  CardContent,
  CardMedia,
  makeStyles,
  Typography,
} from '@material-ui/core';

const useStyles = makeStyles(theme => ({
  media: {
    height: 140,
  },
  title: {
    height: 50,
    overflow: 'hidden',
    textOverflow: 'ellipsis',
  },  
  description: {
    height: 50,
    overflow: 'hidden',
    textOverflow: 'ellipsis',
  },
}));

const ContentThumbnail = ({ image, title, description, date }) => {
  const classes = useStyles();
  return (
    <Card>
      <CardActionArea>
        <CardMedia
          image={image}
          title=""
          className={classes.media}
        />
        <CardContent>
          <Typography gutterBottom variant="h5" component="h2" className={classes.title}>
            {title}
          </Typography>
          <Typography variant="body2" component="p" className={classes.description}>
            {description}
          </Typography>
        </CardContent>
      </CardActionArea>
    </Card>
  );
};


export default ContentThumbnail;
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Katie7
  • 759
  • 1
  • 19
  • 34

1 Answers1

2

Unfortunately you cannot add elipsis on a multiple lines, it is applicable per single horizontal line.

One workaround is to calculate the total number of symbols you can have before showing the elipsis.

In your code you can have

const [description, setDescription] = useState('');
const MAX_SYMBOLS_ALLOWED = 50;

useEffect(() => {
  if(description.length >= MAX_SYMBOLS_ALLOWED) {
    // 3 is for the number of dots ( the elipsis )
    const transformed = description.substr(0, MAX_SYMBOLS_ALLOWED - 2);

    setDescription(`${transformed}...`)
  }

}, [description])
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>
  • Thanks so much Tyhomira. This is certainly a useful option for me to consider if I can't achieve the truncation by line height or even em (width of the characters). And it's useful to know that the CSS is only applicable to a single line. Thank you once again :) – Katie7 Dec 03 '20 at 15:14