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:

https://i.sstatic.net/GHLNd.jpg

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 is the best way to focus the video on its center while simultaneously cropping the edges to keep it in its original position and size?

I'm trying to create a special design element: a muted video that zooms in when the mouse hovers over it, but remains the same size as it is clipped at the edges. It would be even more impressive if the video could zoom in towards the point where the ...

Error Encountered in Vue.js when Trying to Access a Nested

Below is a snippet of my route code from app.js let routes = [{ path: "/dashboard", component: require("./components/Dashboard.vue") }, { path: "/tour", component: require("./components/Index.vue"), children: [{ name: &apos ...

What steps can I take to display a download button when a file is clicked on?

As a backend developer, I usually don't delve into JavaScript tasks, but I have a simple query for JavaScript developers that I need help with. Here is my question: I am trying to display a download button when a specific file is clicked using jQuery ...

Performing addition and subtraction calculations with HTML and Javascript

I need help creating a simple HTML table for adding and subtracting values, with a limit of 10 and a minimum of 0. I have two functions set up, additionalAdd and additionalSub, triggered by the onclick event, but I keep getting an error saying that totalAd ...

Encountering an issue while trying to utilize the firestorePlugin from vuefire in Vuejs 3 createApp. The problem is that I am receiving an Uncaught TypeError: Cannot set property '$

I recently encountered an issue in my Vue.js 3 app with the following code snippet in my main.js file: import { createApp } from "vue"; import App from "./App.vue"; import { firestorePlugin } from "vuefire"; const app = creat ...

Combining v1 and "next" versions in Material UI for optimal performance

Is it possible to seamlessly integrate the newly released "next" components from the "next" branch of Material UI with our current v1 components, and gradually transition our legacy components to the "next" as they are released? Are there any compatibili ...

Populate the dropdown menu with data from a JSON file

Recently, I created a custom JSON file and wanted to populate a select>option using this data. However, I encountered an error message saying: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///C:/.../p ...

Instant Access to a Precise Slide

Using a slider named mySlider or SL_Slider, which is powered by the MooTools library. When on the page with the slider, there is a simple script for the href to call the appropriate slide: <a href="javascript:mySlider.numPress(3);">link</a> ...

Changing json into another format

I am struggling with a JSON data format issue. I have tried using Object.values and object.keys along with Array.prototype.map(), but my algorithm is not producing the desired outcome. [ { "2018-01-01": [ { "firstname": "mati", "lastname": "mati ...

Display the accurate prompt in the event of 2 `catch` statements

elementX.isPresent() .then(() => { elementX.all(by.cssContainingText('option', text)).click() .catch(error => { throw {message: "Unable to select text in dropdown box"} ...

I'm working on a CSS project and my goal is to ensure that all the items are perfectly aligned in a

I have been working on a ReactJS code and I'm struggling to achieve the desired result. Specifically, I am using Material UI tabs and I want them to be aligned in line with an icon. The goal is to have the tabs and the ArrowBackIcon in perfect alignme ...

The importance of adding ".$" to an AngularJS filter object

I have been exploring a section of code related to filtering in AngularJS from the documentation website. (cf. http://docs.angularjs.org/api/ng.filter:filter) Specifically, I am curious about the use of .$ appended to the object search, as shown in the fo ...

When the user clicks on the element, swap out the current image tag

Is it possible to replace the <img src> code in a textarea with image URLs when a button is clicked? <textarea> <img src="https://example.com/image1.gif" alt="image1" /></a> <img src="https://example.com/image2.gif" alt="ima ...

Is it possible to use bootstrap to hide specific components depending on the size of the media screen?

Struggling with styling responsiveness and hoping to find a Bootstrap class that can easily hide components on medium and small screens. I'm looking for a way to hide headings, paragraphs, buttons, and more without any extra hassle. ...

In the `componentDidUpdate()` method, the function `this.props` is not

I've encountered a peculiar issue that I just can't seem to figure out. It's possible that I missed something simple, but I'm stuck trying to solve this bug. Here's what's happening: In the child component, a counter is being ...

Creating objects in separate JavaScript files and including them in the main file, along with their

Following the creation of a config.js file with an object named contextTokenObject, modifications and additions need to be made to this context object from another file (specifically when creating a passport strategy). In the 'passport.js' file, ...

Is query result caching implemented in the Next.js API route?

I have a Next.js application that is connected to a third-party API in order to display certain information. The data is retrieved through Next.js API routes, and the code for this can be found in /pages/api/data.js. const handler = async (req, res) => ...

Tips for utilizing the Toggle Slider JS functionality

I'm attempting to change a value using a slider in HTML, here is my approach: html file : <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script scr="./scripts.js" ...

File uploading feature in Bootstrap (without the need for Javascript)

While I've seen this question posted in a similar style before, one critical point (in my opinion) hasn't been addressed - is there a way to achieve this without using JavaScript? On mobile devices, overscripted sites can sometimes have non-worki ...

Adding a padding-left to a horizontal list within Flexbox enhances the design and structure

How can the left-padding added by Flexbox on a horizontal list be fixed even with justify-content: space-between? <div class="list-container"> <ul> <li>One</li> <li>Two</li> <li>Three</li> ...