Alexander Vovolka
Alexander Vovolka

Reputation: 53

material-ui how to override nested styles

I have a simple Material-UI component

    <Chip
      avatar={
        <Avatar>
          <TruckIcon color='primary' />
        </Avatar>
      }
      label={name}
      color='primary'
    />

the following styles applied from mui-theme:

.MuiChip-root .MuiChip-avatarColorPrimary {
    color: #fff;
    background-color: #21349f;
}

The question is how to override it?

I have tried many options in my theme override styles:

MuiChip: {
 avatarColorPrimary : {
  background-color: red;
}


    MuiChip: {
      root: {
        avatarColorPrimary  : {
           background-color: red;
          }
       }
    }

MuiChip: {
 '& .avatarColorPrimary': {
  background-color: red;
}

but none of them is working. I'm using 4.9.5 version of Material-UI.

Upvotes: 3

Views: 5275

Answers (1)

Ryan Cogswell
Ryan Cogswell

Reputation: 81016

The most useful resource when trying to determine the appropriate way to override a style is to look at how the default styles are defined in the source code.

Below is an excerpt of the default styles from the Chip source code:

{
   root: {
     '& $avatarColorPrimary': {
        color: theme.palette.primary.contrastText,
        backgroundColor: theme.palette.primary.dark,
      }
   }
}

Below is an example of overriding the background color in the theme:

import React from "react";
import { createMuiTheme, ThemeProvider } from "@material-ui/core/styles";
import Avatar from "@material-ui/core/Avatar";
import Chip from "@material-ui/core/Chip";
import DoneIcon from "@material-ui/icons/Done";

const theme = createMuiTheme({
  overrides: {
    MuiChip: {
      root: {
        "& $avatarColorPrimary": {
          backgroundColor: "red"
        }
      }
    }
  }
});

export default function Chips() {
  return (
    <ThemeProvider theme={theme}>
      <Chip
        avatar={
          <Avatar>
            <DoneIcon color="primary" />
          </Avatar>
        }
        label="Sample Name"
        color="primary"
      />
    </ThemeProvider>
  );
}

Edit Chip avatar background

Upvotes: 2

Related Questions