Is there a way to customize the color of a MUI styled component?

I have a customized MUI component that displays a circular badge in green.

const StyledGreenBadge = styled(Badge)(({ theme }) => ({
    '& .MuiBadge-badge': {
      backgroundColor: '#44b700',
      color: '#44b700',
      width: '15px',
      height: '15px',
      borderRadius: '100%',
      boxShadow: `0 0 0 2px ${theme.palette.background.paper}`,
      '&::after': {
        position: 'absolute',
        top: 0,
        left: 0,
        width: '100%',
        height: '100%',
        borderRadius: '50%',
        animation: 'ripple 1.2s infinite ease-in-out',
        border: '1px solid currentColor',
        content: '""',
      },
    },
    '@keyframes ripple': {
      '0%': {
        transform: 'scale(.8)',
        opacity: 1,
      },
      '100%': {
        transform: 'scale(2.4)',
        opacity: 0,
      },
    },
  }));

Now, I am looking to refactor my code to avoid repetition by creating a StyledYellowBadge.

All I want to do is change the color property of StyledGreenBadge dynamically.

However, after spending several hours attempting various methods, I still couldn't find a solution.

I attempted something like this:

color: { desiredColor === 'yellow' ? 'yellow' : #44b700'},

where desiredColor comes as a second argument after

{ theme }

Can someone guide me on how to accomplish this?

Answer №1

If you want to customize properties for your MUI component, you can do so by specifying the type:

const StyledGreenBadge = styled(Badge)<{ badgeColor?: string }>(

Next, you can provide the specified property (badgeColor in this example) to your styled Badge component:

 <StyledGreenBadge badgeColor="red" badgeContent={4} color="primary">

and then assign it to the desired property:

  backgroundColor: props.badgeColor ?? "#44b700",

Complete code snippet:


const StyledGreenBadge = styled(Badge)<{ badgeColor: string }>(
  ({ theme, ...props }) => {
    console.log(props);
    return {
      "& .MuiBadge-badge": {
        backgroundColor: props.badgeColor ?? "#44b700",
        color: "#44b700",
        width: "15px",
        height: "15px",
        borderRadius: "100%",
        boxShadow: `0 0 0 2px ${theme.palette.background.paper}`,
        "&::after": {
          position: "absolute",
          top: 0,
          left: 0,
          width: "100%",
          height: "100%",
          borderRadius: "50%",
          animation: "ripple 1.2s infinite ease-in-out",
          border: "1px solid currentColor",
          content: '""'
        }
      },
      "@keyframes ripple": {
        "0%": {
          transform: "scale(.8)",
          opacity: 1
        },
        "100%": {
          transform: "scale(2.4)",
          opacity: 0
        }
      }
    };
  }
);

export default function SimpleBadge() {
  return (
    <StyledGreenBadge badgeColor="red" badgeContent={4} color="primary">
      <MailIcon color="action" />
    </StyledGreenBadge>
  );
}

Check out the demo here

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

Using a JavaScript if statement to check the height of a specific HTML element

I have been struggling to figure out how to insert an if-else statement in JavaScript that references data about an HTML element. My objective is to create an "onclick" function that enlarges an image with a 200ms delay and another function that returns th ...

Is it possible to toggle the status of two components simultaneously by pressing a single button?

I'm looking to create a series of onboarding modals using React and MUI. My goal is to transition from one modal to the next when a button within the modal is clicked. While I have explored some packages, they seem too complex for my needs. Can anyone ...

Issues with loading NextJS videos can occur when accessing a page through a link, as the videos may fail to load without

Issue Greetings. The problem arises when attempting to load muse.ai videos on-page, specifically when accessing the page with a video embedded through a NextJS link. To showcase this issue, I have provided a minimal reproducible example on StackBlitz her ...

Managing JSON Forms using jQuery on Google's App Engine

Having difficulty getting jQuery to function properly on GAE in python 2.7. The main issue is that jQuery is unable to retrieve the json data sent by the server. A basic comment form with no special features: <form action="/postcomment/" method="post" ...

Tips for sending a JavaScript variable within a div's ID in a Twig loop?

How can I insert a JavaScript variable into the ID of a div inside a Twig loop? Here is my unsuccessful attempt: <script type="text/javascript"> id = 0; </script> {% for element in parent.elements %} <div id="mydiv"> ...

During the installation process of Next JS, I faced a challenge that hindered

While setting up NextJS, I ran into the following issue: D:\Codes\React\Learn>npx create-next-app npm WARN using --force Recommended protections disabled. npm WARN using --force Recommended protections disabled. npm ERR! code E404 npm ERR ...

What is the process for crafting a Vuejs controlled input form?

Although I am familiar with creating controlled components in React using state, I am new to the Vue framework and would like to understand how to adapt my code from React to be compatible with Vue. My goal is to store the values of input fields in a data ...

Guide on changing the content type of a Response header in a Next.js API route

I am currently working on a Next.js 14 app router and have a requirement to dynamically create an XML file when the API route is called and send it in response. Below is my code snippet: export async function GET(req: NextApiRequest, res: NextApiResponse) ...

Ensure that parameters are validated correctly in the Next.JS application router using the searchParams method

When building the page, I need to properly validate params in the Next.JS app router using searchParams. My goal is to show a main image (coverImage) for each photo on the /gallery page. When a photo is clicked, I want to display more photos of the same k ...

Image-switching button

I'm new to JavaScript and struggling with my first code. I've been staring at it for two days now, but can't figure out what's wrong. The goal is to create an HTML page where the user can change an image by clicking on a button, and th ...

What measures can be taken to stop LESS partials from compiling independently?

When working with LESS, I utilize partials that are included (@include) into the main LESS stylesheet. A common issue I face is that each partial ends up compiling to its own CSS file, leading to project clutter. In SASS, if a file is named with an unders ...

What are some methods for testing enzyme, react-virtualized, and material-ui components?

I am facing a unique testing scenario where I need to interact with a component wrapped in TreeView from material-ui that is nested inside the List component from react-virtualized. Here is my approach: wrapper .find(TreeView) .dive() .find(AutoSiz ...

When the React functional component changes its state, it triggers the un-mounting and re-mounting of its parent

I created a functional component that allows for toggling the visibility of a password field using a small button that switches between closed and opened eye images. The issue I'm facing is that even though the parent does not have any affected state ...

Uncovering the Depths of React Native Background Services

While using Firebase, I want my app to push notifications when new data is added to the database while it's in the background. Currently, I've implemented the following code: message.on('child_added', function(data) { pushNotificatio ...

Submitting forms using AJAX in Django

I am getting a 'Not Ajax' response every time I try to submit my form. There must be something small that I'm overlooking... class VideoLikeView(View): def post(self, request): if request.is_ajax(): message = 'Aj ...

AssistanceBubble.js with ASP.NET UpdatePanel

Looking for guidance on implementing HelpBalloon.js () within an ASP.NET UpdatePanel. Experiencing issues with image loss after a postback. ...

Express (generator) is failing to load custom scripts located in the public folder

I'm new to node and express and I'm facing a problem. I want to load a custom script.js from the public folder, but it's not loading. There are no errors in the console or anything in the network tab. When I try to access the URL localhost:3 ...

Issue with anchor tag not functioning properly within toggle div

Can you please help me troubleshoot why the anchor tag is not functioning properly within my div elements? When I click on the first div, the second div is displayed but the anchor tag inside the first div does not seem to be working. <script> $(&ap ...

Tips for accurately relocating elements within a tooltip

Currently, I am working on implementing a like model within a Rails application. In order to display which user liked the bonus, I have incorporated foundation tooltip. Below is the code snippet: - avatars = bonus.like_user_avatars.map { |avatar| image_t ...

Resizing an image with six corners using the canvas technique

Currently, I am facing two issues: The topcenter, bottomcenter, left and right anchors are not clickable. I'm struggling with the logic to adjust the image size proportionally as described below: The corner anchors should resize both height and wi ...