React Material UI CardHeader title overflow with dots

Issue

How can I properly add dots the the title in my Cardheader if it exceeds the parents width (Card width). So far I have done this:

  card: {
    width: 275,
    display: "flex"
  },

  overflowWithDots: {
    textOverflow: 'ellipsis',
    whiteSpace: 'nowrap',
    overflow: 'hidden',
    width: '100px'
  }

  <Card className={classes.card}>
    <CardHeader
       title={
         <Typography gutterBottom variant="h6" component="h4" className={classes.overflowWithDots}>
        {movie.title}
        </Typography>
       }
   />

This works in a way, but I have to tell the class to have a width of 100px until it adds the dots. I need to add the dots if it exceeds the parents width.

Solution

Problem

As I understand it you are limiting the size of the Card, in this case, you are not being able to place the ellipsis due to the way the CardHeader is rendered in the html.

The CardHeader component is rendered with a “root” element and a “content” element. See below:

CardHeader rendered

Typography has a built-in prop to adding dots noWrap. For the noWrap property to work correctly, we have the following approaches.

Solution 1

CardHeader’s default behavior is to use flex. If you don’t need it use flex:

...

cardHeader: {
  display: "block",
  overflow: "hidden"
}

...

<CardHeader
  className={classes.cardHeader} 
  title={
        <Typography noWrap gutterBottom variant="h6" component="h4">
           A world wide web - the revolution
        </Typography>
        }
/>
...

Solution 2

If you need to keep CardHeader with flex behavior, in this case, the overflow needs to be applied to the root and content. To reach the elements use the CardHeader classes property passing the generated class to the content prop.

...

cardHeaderRoot: {
  overflow: "hidden"
},
cardHeaderContent: {
  overflow: "hidden"
}

...

<CardHeader
  classes={{
           root: classes.cardHeaderRoot,
           content: classes.cardHeaderContent
         }}
  title={
        <Typography noWrap gutterBottom variant="h6" component="h4">
           A world wide web - the revolution
        </Typography>
        }
/>

...

Here’s an example in the sandbox.

Edit Button

Atention

Be aware that by modifying the default behavior of how components are rendered, some side effects may occur in your entire component tree.

Anyway

If you still have any problems let us know.

Answered By – Jairon Alves Lima

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published