Categories
React Answers

How to fix the custom color to Badge component not working with React Material UI?

Spread the love

Sometimes, we want to fix the custom color to Badge component not working with React Material UI.

In this article, we’ll look at how to fix the custom color to Badge component not working with React Material UI.

How to fix the custom color to Badge component not working with React Material UI?

To fix the custom color to Badge component not working with React Material UI, we can use the styled function to create a badge component with custom styling.

For instance, we write:

import React from "react";
import Badge from "@material-ui/core/Badge";
import MailIcon from "@material-ui/icons/Mail";
import { styled } from "@material-ui/core";

const StyledBadge = styled(Badge)({
  "& .MuiBadge-badge": {
    color: "yellow",
    backgroundColor: "green"
  }
});

export default function App() {
  return (
    <StyledBadge badgeContent={130}>
      <MailIcon />
    </StyledBadge>
  );
}

We call styled with Badge to return a function that we call with an object that has the custom badge styles.

We select the badge with the "& .MuiBadge-badge" selector.

And we set the color to 'yellow' and backgroundColor to 'green'.

Finally, we use the StyledBadge component that’s returned by styled with the badgeContent prop to add content into the badge.

And we should see that the badge text is yellow and the badge background is green.

Conclusion

To fix the custom color to Badge component not working with React Material UI, we can use the styled function to create a badge component with custom styling.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *