Dots are used to indicate overflow of title in React Material UI CardHeader

Is there a way to add ellipsis dots to the title in my Cardheader when it exceeds the parent's width (Card width)? Here is what I have attempted so far:


  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>
       }
   />

While this solution works, I have to manually set the class width to 100px for the dots to appear. How can I automatically add the dots when the title exceeds the parent element's width?

Answer №1

Even though the solution provided here is effective, for those utilizing mui v5, you can achieve the same result using the sx prop explained in this guide. By adjusting the .MuiCardHeader-content style and the titleTypographyProps prop, you can customize the title as desired. Additionally, I included an action button and subheader for further illustration.

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;

If you want to experiment with this implementation, feel free to visit the sandbox.

Answer №2

Issue

It appears that the limitation in placing ellipsis on the Card is due to the rendering of the CardHeader component in the HTML structure.

The CardHeader consists of a "root" element and a "content" element as shown below:

The Typography component has a built-in prop for adding ellipsis, called noWrap. In order for the noWrap property to function correctly, there are two possible solutions outlined below:

Option 1

If you do not require the flex behavior of CardHeader, you can disable it by setting the display property to "block" and overflow property to "hidden":

...

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

...

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

Option 2

If you need to maintain the flex behavior of CardHeader, you can apply the overflow to both the root and content elements using the generated classes from the CardHeader classes property:

...

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>
        }
/>

...

You can view an example in the provided sandbox link.

Note

Please be cautious when modifying the default rendering behavior of components, as it may lead to unintended side effects across your component tree.

Final Thoughts

If you encounter any further issues, feel free to reach out to us for assistance.

Answer №3

Utilize Typography's built-in feature for adding ellipsis. Simply include the noWrap prop to Typography within your CardHeader component. This will automatically add ellipsis to the header text based on the width of the parent component.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are the steps to resolve the issue of assigning void type to type ((event: MouseEvent<HTMLDivElement, MouseEvent>) => void) | undefined in a react application?

I'm trying to update the state isOpen to true or false when clicking on a div element, but I keep getting an error with the following code: function Parent() { const [isOpen, setIsOpen] = React.useState(false); return ( <Wrapper> ...

Acquiring data from a separate Redux slice and utilizing it as the default state in a distinct slice

In my application, I have two Redux slices called userSlice and cartSlice. My goal is to extract the specific value userName from the userSlice and use it as the initial value for a property named user in the cartSlice. Despite my efforts, I am encounterin ...

Node.js powered file uploading on the Heroku platform

After attempting to upload a file to Heroku using https://www.npmjs.com/package/express-fileupload, I encountered an error. It worked fine on my PC, but on Heroku, I received the following error message: {"errno":-2,"code":"ENOENT","syscall":"open","path" ...

Oops! The `source` prop provided to the `Image` component in React Native is invalid

Is it possible to receive assistance in React Native? I keep getting this error from the compiler: "Failed prop type: Invalid prop source supplied to Image" The 'dec' variable is a string fetched from an API. Please provide some guida ...

What is the best way to ensure that my image completely occupies the div?

I am facing a challenge in creating a hero image that would completely fill the div on my webpage. Despite setting the width and height to 100%, the image seems to only occupy half of the space. Check out the CSS and HTML code snippet here. div.hero{ ...

Encountering an issue when trying to retrieve the "createdAt" property in Cloud Code using the Parse Framework

I am working with Cloude Code to develop a more complex query, but I am having trouble accessing the automatically created "createdAt" property by Parse. Here is my code: Parse.Cloud.define("get_time", function(request, response) { var query = new Par ...

Interactive menu backdrop determined by div element

I am working on a website with a menu structured like the following: Home -- Work -- Pricing -- Contact Us -- About This website uses a one-page layout and has enabled Scrollspy on Bootstrap. I need to make the active menu background dynamic depending o ...

Connecting a Specific Keyboard Key to a Function in a React JS Environment

I have created a simple App that you can view here. However, I am facing an issue with the functionality. When a user is logged in and creating a post, they can press a button to add a post. Now, I want the "Enter" key to perform the same action as the but ...

JavaScript promises do not guarantee the execution of the loop

There was a block of Javascript code that I needed to modify. Initially, the code looked like this: if(!this.top3){ const promises = this.images.map((el, index) => { return this.getData(el.title, index); }); return Promise.all(promise ...

Type of variable that is not an array

I need a quick way to check if a value is an object {} but not an array []. The code I currently have is: function isPlainObject(input) { return !Array.isArray(input) && typeof input === 'object'; } Is there a more concise method to a ...

Hovering over a Raphael animation - What's preventing it from functioning?

I'm currently working on a pie chart using Raphael, and I want to add a tooltip that displays text when hovering over a specific segment of the chart. The hover event is functioning correctly, but I'm having trouble adjusting the tooltip text coo ...

What steps can be taken to ensure that the v-model input is not updated?

Typically, when a user enters a value in an input field, it automatically updates a model. However, I am looking to temporarily prevent this automatic update. In my application, I have a canvas where users can draw grids by entering lengths and widths in i ...

The DataGrid is only displaying a single result instead of multiple results

I'm having difficulty displaying all the results in this MUI data table. Currently, it is only showing one result instead of all, and I can't figure out what I'm doing wrong. If you have any suggestions or best practices on how to properly ...

How to create a non-clickable section within a linked div

Website: I am interested in linking just the triangle banner located at the top right corner of the page. The triangle image is actually a transparent rectangle with only the triangle portion filled in, so I want to ensure that only that particular sectio ...

What is the reason behind MUI DatePicker only displaying the year with a single digit?

I am facing an issue while setting up a registration form with MUI Fields. The input Field for the date is not functioning properly. When I enter a date, the days and month are passed correctly, but the year only captures the digit that was entered. For ex ...

Formatting a pair of elements side by side in MUI Select

Currently, I am tackling the challenge of organizing elements in MUI Select v4. My goal is to display these elements in two columns rather than just one column within the dropdown. Despite attempting to override certain styles within MUI, I have not been ...

Manipulate SVG elements by dragging them along the boundary of the path

Looking to achieve a specific functionality where I can drag and drop an element along the edges of a drawn path, rather than inside the path itself. To clarify, the goal is to move the red marked element on the black line bordering the path, allowing move ...

React.js TypeScript Error: Property 'toLowerCase' cannot be used on type 'never'

In my ReactJS project with TSX, I encountered an issue while trying to filter data using multiple key values. The main component Cards.tsx is the parent, and the child component is ShipmentCard.tsx. The error message I'm receiving is 'Property &a ...

Issues with login validation in HTML when utilizing JSON and PHP

While creating a login form in HTML using JSON and PHP, I encountered an issue where the if statements in the success function were not working properly. However, the beforeSend and error functions are functioning as expected. Can someone assist me in iden ...

ng-if is executed prior to the specified time

This unique Soundcloud player was created using Plangular, a directive that utilizes AngularJS and the Soundcloud API. Due to certain restrictions with third party apps not being able to stream some Soundcloud tracks, I have implemented ng-if="track" and n ...