Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Material UI CardHeader title overflow with dots

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.

like image 810
user13262487 Avatar asked Apr 18 '26 09:04

user13262487


1 Answers

Although this solution works, if you are using mui v5, this is how you can do it using the sx prop described here. You can set the .MuiCardHeader-content style and titleTypographyProps prop to style the title. I added an action button and subheader as an extra example.

import React from "react";
import { Card, CardHeader, IconButton } from "@mui/material";
import { MoreVert as MoreVertIcon } from "@mui/icons-material";

const SimpleCard = () => (
  <Card sx={{ width: "275px", display: "flex" }}>
    <CardHeader
      sx={{
        display: "flex",
        overflow: "hidden",
        "& .MuiCardHeader-content": {
          overflow: "hidden"
        }
      }}
      title={"A very long title coooooooooooooool"}
      titleTypographyProps={{ noWrap: true }}
      subheader={"ps long subheader cooooooooooooool"}
      subheaderTypographyProps={{ noWrap: true }}
      action={
        <IconButton>
          <MoreVertIcon />
        </IconButton>
      }
    />
  </Card>
);

export default SimpleCard;

Here's the sandbox to mess around with.

like image 81
Kevo1ution Avatar answered Apr 20 '26 23:04

Kevo1ution