Search code examples
cssstylesmaterial-uioverflowtypography

In MaterialUI, how do I apply a class to my Typography element?


In my material-ui component, I want to create an ellipsis when my Typography element overflows. I created these styles ...

const styles = (theme) => ({
  root: {
    textAlign: "left",
    margin: theme.spacing(2),
    paddingBottom: theme.spacing(1),
    color: theme.color.secondary,
  },
  cardHeader: {
    paddingBottom: theme.spacing(0),
  },
  cardContent: {
    paddingBottom: theme.spacing(1),
  },
  rowBody: {
    width: "100%",
    flexWrap: "nowrap",
    alignItems: "center",
    display: "flex",
  },
  halfRow: {
    width: "50%",
  },
  address: {
    "& .MuiTypography-h5": {
      textOverflow: "ellipsis",
      overflow: "hidden",
    },
  }

and I applied the "address" class to my Typography element like so

            <Typography variant="h5" className={classes.address}>
              <a href={`https://www.google.com/maps/dir/"${location}"`}>{location}</a>
            </Typography>

However, the ellipsis is not appearing and the element is wrapping

enter image description here

What else do I need to do to apply a style to my Typography element?


Solution

  • Your address class should be added to the parent of the Typography component else the style chaining won't work.

    address: {
        "& .MuiTypography-h5": {
          textOverflow: "ellipsis",
          overflow: "hidden",
        },
      }
    

    What it means is that find a class .MuiTypography-h5 inside address class and apply the style but there isn't any.

    Also I recommend you use makeStyles to create styles.

    const styles = makeStyles(theme => ({
      address: {
        "& .MuiTypography-h5": {
          textOverflow: "ellipsis",
          overflow: "hidden"
        }
      }
    }));
    export default function App() {
      const classes = styles();
      return (
        <div className={classes.address}>
          <Typography variant="h5">
            126 Phillips Key Suite 042 West Kentucky
          </Typography>
        </div>
      );
    }