Search code examples
cssmaterial-uistyled-components

With styled-components, how can I target a child class of a component?


I'm using a mui Badge component and I want to style the little circle. I have:

const BadgeStyled = styled(Badge)`
  & > .muibadge-badge: {
    background-color: #d3d4d7;
    width: 15px;
    height: 15px;
  }
`;

The generated HTML is:


    <span class="MuiBadge-root BaseBadge-root css-1o9b3gb-MuiBadge-root">
    ... some stuff
<span class="MuiTouchRipple-root css-8je8zh-MuiTouchRipple-root"></span>
</button>
<div class="MuiAvatar-root MuiAvatar-circular MuiAvatar-colorDefault css-f84387-MuiAvatar-root">
   <span class="MuiTypography-root MuiTypography-eyebrowSmall css-1bcwatu-MuiTypography-root">J</span>
</div>
<span class="MuiBadge-badge MuiBadge-standard MuiBadge-anchorOriginTopRight MuiBadge-anchorOriginTopRightRectangular MuiBadge-overlapRectangular MuiBadge-colorPrimary BaseBadge-badge css-1es1533-MuiBadge-badge">4</span>
</span>


So I have MuiBadge-badge in the generated HTML, but my style doesn't seem to apply. Any tips would be greatly appreciated! Thanks!


Solution

  • Your syntax is wrong, have a look at this working codesandbox

    Here is how you can style the Badge component

    const BadgeStyled = styled(Badge)({
      "& .MuiBadge-badge": {
        backgroundColor: "#d3d4d7",
        width: '15px',
        height: '15px',
      }
    });