Customizing existing Mui classes through the use of makeStyles

Recently, I made a small change in my approach to styling by moving CSS directly into my component files using styled components, emotion, and make styles. This decision was driven by the benefits of easier management and improved development experience. As I experimented with this new method on a dummy project and then on some components of a current app I'm working on, I encountered an issue with overriding existing Material-UI styles.

For instance, while creating an accordion component using Material-UI, I came across a nested property:

.MuiAccordionSummary-root.Mui-expanded {
    min-height: 64px;
}

Adjusting this in my sass file would have been simple, but I struggled to figure out how to implement it using make styles.

My current styles are structured like this:

const useStyles = makeStyles((theme) => ({
  root: {
    borderBottom: '0.5px solid',
    borderBottomColor: theme.palette.primary.main,
    marginBottom: '16px',
    maxHeight: '35px',
  },
  summary: {
    backgroundColor: theme.palette.complimentory.main,
    borderBottom: '0.5px solid',
    borderBottomColor: theme.palette.primary.main,
    maxHeight: '35px',
    height: '35px',
  },
  title: {
    fontFamily: 'Helvetica',
    fontStyle: 'normal',
    fontWeight: 'normal',
    fontSize: '14px',
    lineHeight: '14px',
    letterSpacing: '0.266667px',
    textTransform: 'uppercase',
  },
  content: {
    marginTop: '15px',
    fontSize: '14px',
    fontStyle: 'normal',
    lineHeight: '16.8px',
    letterSpacing: '0.375px',
    fontWeight: '400',
    fontFamily: 'Helvetica',
    textAlign: 'left',
  },
}))

I am struggling to target the specific MuiAccordionSummary element inside makestyles. It seems possible, but I'm finding it challenging due to my lack of familiarity with this method.

Answer №1

To ensure proper styling in your project, make sure to include

<StyledEngineProvider injectFirst>
at the root level

import { render } from "react-dom";
import { StyledEngineProvider } from "@mui/material";
import App from "./App";

const rootElement = document.getElementById("root");
render(
  <StyledEngineProvider injectFirst>
    <App />{" "}
  </StyledEngineProvider>,
  rootElement
);
import * as React from "react";
import AppBar from "@mui/material/AppBar";
import Box from "@mui/material/Box";
import Toolbar from "@mui/material/Toolbar";
import Typography from "@mui/material/Typography";
import Button from "@mui/material/Button";
import IconButton from "@mui/material/IconButton";
import MenuIcon from "@mui/icons-material/Menu";
import makeStyles from "@mui/styles/makeStyles";

const useStyles = makeStyles((theme) => {
  return {
    root: {
      backgroundColor: "red",
      color: "pink"
    }
  };
});

export default function App() {
  const classes = useStyles();
  return (
    <Box sx={{ flexGrow: 1 }}>
      <AppBar position="static" className={classes.root}>
        <Toolbar>
          <IconButton
            size="large"
            edge="start"
            color="inherit"
            aria-label="menu"
            sx={{ mr: 2 }}
          >
            <MenuIcon />
          </IconButton>
          <Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
            News
          </Typography>
          <Button color="inherit">Login</Button>
        </Toolbar>
      </AppBar>
    </Box>
  );
}


View a working demo here https://codesandbox.io/s/wizardly-stonebraker-qnh3t

Answer №2

If you want to customize the styles of the AccordionSummary component in Material UI, you can easily do so by overriding existing CSS rules. The Accordion Summary provides 6 specific CSS rules that you can override: root, expanded, focused, disabled, content, and expandIcon. These rules are detailed in the CSS section of the AccordionSummary API page on Material UI's official documentation.

Each CSS rule corresponds to a Material UI class for the respective component. For example, the root rule for the AccordionSummary component corresponds to the class .MuiAccordionSummary-root. To override these styles, you can use the method of overriding styles with classes.

Here is an example utilizing this method:

  1. Create a custom class and define the styling using makeStyles. In this case, we will create a class called summaryExpanded with the styling minHeight: '64px'.
const useStyles = makeStyles((theme) => ({
  root: {
    borderBottom: '0.5px solid',
    borderBottomColor: theme.palette.primary.main,
    marginBottom: '16px',
    maxHeight: '35px',
  },
  summary: {
    backgroundColor: theme.palette.complimentory.main,
    borderBottom: '0.5px solid',
    borderBottomColor: theme.palette.primary.main,
    maxHeight: '35px',
    height: '35px',
  },
  summaryExpanded: {
    minHeight: '64px',
  },
  title: {
    fontFamily: 'Helvetica',
    fontStyle: 'normal',
    fontWeight: 'normal',
    fontSize: '14px',
    lineHeight: '14px',
    letterSpacing: '0.266667px',
    textTransform: 'uppercase',
  },
  content: {
    marginTop: '15px',
    fontSize: '14px',
    fontStyle: 'normal',
    lineHeight: '16.8px',
    letterSpacing: '0.375px',
    fontWeight: '400',
    fontFamily: 'Helvetica',
    textAlign: 'left',
  },
}))
  1. Apply the custom style to the AccordionSummary component by assigning your custom class to the relevant rule name. In this case, we want to override the Mui-expanded class in the AccordionSummary component with our summaryExpanded class.
const classes = useStyles();

<Accordion>
  <AccordionSummary
    classes: {{
      expanded: classes.summaryExpanded,
    }}
  >
  </AccordionSummary>
  <AccordionDetail>
  </AccordionDetail>
</Accordion>

Answer №3

If you're looking to customize styles, try experimenting with overriding properties.

import { Overrides } from "@material-ui/core/styles/overrides";

const customizedStyles: Overrides = {
  MuiExpansionPanelSummary: {
    root: {
      minHeight: "3rem",
      "&$expanded": {
        minHeight: "3rem",
      },
    },
    content: {
      margin: "0.3rem",
      "&$expanded": {
        margin: "0.3rem",
      },
    },
    expandIcon: {
      padding: "0.4rem",
    },
    expanded: {},
  },
};

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

Can I apply MUI's touch ripple effect to a div element?

After browsing through various responses to similar queries, I noticed that most of them are outdated and no longer applicable to the latest version of MUI. I'm looking for a way to add the touch ripple effect to a div element, but I can't use a ...

Here is a simple guide on how to create a button that

const myStyles = makeStyles({ buttonDesign: { color: "blue", background: "white", "&hover": { transform: "scale(10%)"", background: "white", }, }, }); I want the bu ...

Customize the CloseIconButton in Material-UI Autocomplete for a unique touch

Hello everyone, I have a simple dilemma. I am trying to implement a custom closeIconButton, but the only available prop is closeIcon. However, this prop is not sufficient because I need this custom button to also have an onClick property. If I add the onC ...

What is the solution for the error message "Unhandled Runtime Error" with the description "TypeError: videoRef.current.play is not a function"?

I am currently working on implementing custom controls for a video on a Nextjs website. When using a standard HTML <video> component, the code functions as expected and clicking the custom play button successfully plays the video. However, when I swi ...

How to create a self-contained div in VueJS using Tailwind CSS without affecting other elements

I'm feeling completely overwhelmed right now. Attached is a picture showing the issue I'm facing: The user list layout is on the right The chat content in the middle should be scrollable vertically The bottom div should stay fixed in place witho ...

CSS following a clicked event

http://codepen.io/anon/pen/GqmEAq My goal is to make the 'x' button clicked (the 'x' is created after clicking the plus sign on the menu) and then bring the dropdown back up. I have attempted: a:after:checked ~ .submenu{ max-height ...

LeafletJS and ReactJS integration causing misalignment in tile ordering

In my ReactJS single page application, I am utilizing the LeafletJS plugin to showcase a full-page map. Even after following the guidelines mentioned here, I am facing an issue where the map tiles are not displayed in the correct order and appear to be shu ...

Switching between vertical and horizontal div layouts while reorganizing text fields within the top div

function toggleDivs() { var container = document.querySelector(".container"); var top = document.querySelector(".top"); var bottom = document.querySelector(".bottom"); if (container.style.flexDirection === "column") { container.style.flexDirec ...

React's useState feature is doubling the increment

I have created a basic form management system with a historical feature. A simplified version of this system can be seen on codesandbox import { useState } from "react"; import "./styles.css"; const sample = ["what", "w ...

Tips for aligning a div containing an image in the center of another div

Trying to perfectly center an image inside a div both vertically and horizontally using the display inline-block property. HTML <div class="center-wrapper"> <div class="image-holder"> <img src="picture.jpeg" alt="Centered Image"> ...

Using Bootstrap's dual listbox, you can easily select single options with the ability to add or delete them. Upon selection, the

Could someone please assist me in resolving this issue? I am looking for a dual listbox with single select option, unlike Bootstrap which only offers dual listboxes with single/multiple select. To Clarify: Here is an example: In my dual listbox, the le ...

Issue with dynamically adjusting flex box width using JavaScript

Currently, I am developing a user interface that heavily relies on flexbox. The layout consists of a content area and a sidebar that can be toggled by adding or removing a specific class. Whenever the sidebar is toggled, the content area needs to be manua ...

Comparison between a reusable React hook and a convoluted JavaScript response organization

I am currently developing a web application using React. In my code, I have numerous calls to the database that all share a very similar structure. The only variances among these calls are the table names and parameters, resulting in a multitude of functio ...

Covering a secret link with a backdrop image

I have set a background image in a column on my WordPress site. However, I want to make this image clickable by placing a transparent box over it, as background images cannot be linked directly. #container { background-image: url(https://www.quanser.c ...

Ways to include the Active class in a React sidebar

I recently integrated a sidebar menu using ReactJs and now I am facing a challenge. I want to ensure that when a specific link is clicked, it displays the active_menu class while the others retain their default style. Take a look at my sidebar setup below ...

Properties undefined

All of my functions are giving errors indicating that the props are not defined. The error specifically relates to the word "props" in the following functions: function PostButton(props) function PostButton2(props) function TotalVotes(props) ...

Guide to triggering a change event on a react-number-format component

I am attempting to trigger a change event in order to modify the value of a react-number-format component within my component. During testing, I encounter a TypeError: value.replace is not a function error on the simulate('change', event) method ...

Can someone please tell me the specific HTML entity that Flickr uses for the arrow icons in the action menu?

When viewing an image on FLickr () and clicking on the Actions menu button, a pop-up menu with an arrow icon appears. Interestingly, this icon is not a simple image, but rather a combination of two characters (◢◣). Has anyone been able to determine th ...

Issue with Axios fetching data with parameter in Next.js not resolving

While working with Next.js, I encountered an issue where the input text value (email) is successfully displayed in the console, but when trying to use this value as a parameter, "{emails}" is being saved in the database instead of the dynamic email value. ...

How can recursive data be displayed in a template?

I am working with a model in Django that has a ForeignKey pointing to itself, and I need to display all the data from the database using lists and sublists: Below is my model definition: class Place(models.Model) name = models.CharField(max_length=1 ...