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

Continuing a discussion in Bot Framework leads to an error: Unable to execute 'set' on a proxy that has been invalidated

I've been exploring the Microsoft Teams Bot Framework samples, specifically diving into bot-conversation. The source code for this can be found here. My goal is to send user messages to a backend server using a websocket and then post a response mess ...

How to send the file path to an API in JavaScript to convert it

I am currently working on a web application that allows users to upload a wav file and convert it to mp3 format. I have successfully implemented the wav to mp3 conversion and saving it to the project folder. However, I am facing an issue with dynamically p ...

Modifying an HTML list item to become 'active' in a navigation bar

One way I've been implementing my navbar on each page is by using the following code at the bottom of the page within script tags: $("#navbar-partial").load("navbar.html). The code for the navbar list looks like this: <ul id="main-nav" class="nav ...

I'm encountering a 404 error with Jquery ajax, indicating that the requested resource was not

Check out the code snippet below: <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content=""> <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/ ...

Using Python Selenium to create a login page with Javascript

Attempting to access a page using Python selenium package for certain activities is proving challenging. Despite the following code being written, an error message of "the Class is not found" keeps appearing. To proceed with using send_keys(), it's ne ...

Key attribute in React's li element

I received a caution that each child in an array or iterator should have a unique "key" prop, even though I did use a key. Below is the code snippet causing the issue: return ( <li onClick={this.handleOnMarkAsCompleted} key={Date.now()}> { com ...

Using JavaScript to consume ASP.net Script Services

My ASP.NET script service needs to be accessed from JavaScript using JSONP due to cross-domain restrictions. When dealing with a complex input structure, I have to construct the client-side input structure myself. How does the matching between the client ...

Discovering the size of an attribute in an object using Angular

I am working with a JSON object named "programs" that contains an array of key/value pairs. My task is to determine the count of objects within this array that have the key/value pair "status": "Review". In this case, there are 4 objects in total and 2 o ...

Unable to disable webpack HMR

I have set up my project using express version 4.14.0, webpack version 1.14.0 with babel and its presets. I obtained this sample webpack configuration from a reliable source: var path = require('path'); module.exports = { entry: './main. ...

Clone content upon pressing the Enter key

I am facing an issue with my editable container where I have a div inside it. Whenever I press enter, the div duplicates, resulting in two divs stacked on top of each other. The container has contenteditable set to true, which might be causing this problem ...

Utilizing Typescript for Efficient Autocomplete in React with Google's API

Struggling to align the types between a Google address autocomplete and a React-Bootstrap form, specifically for the ref. class ProfileForm extends React.Component<PropsFromRedux, ProfileFormState> { private myRef = React.createRef<FormContro ...

Creating a stunning display of six video textures on a cube through the power of three.js

My current project involves working with a video that has been segmented into six parts. Here is a screenshot of the input video. The goal is to project these 6 videos onto the six faces of a cube using JavaScript: <!DOCTYPE html> <html> &l ...

The Ajax submit button is only operational for a single use

Check out my basic HTML form and JS setup: <body> <form> <label for="usrtext">Type your text here:</label> <br /> <textarea name="usrtext" id="usrtext" rows="25" cols="100"></textarea> ...

Tips for passing navigator reference to React Native's <Drawer/> component?

Utilizing react-native-drawer ( https://github.com/root-two/react-native-drawer ) in my index.ios.js file, I have the following setup where I am attempting to pass the 'navigator' reference into the <DrawerPanel /> of <Drawer /> compo ...

In what situations is it beneficial to utilize inherited scope, and when is it best to avoid it

Is it better to use inherited scope (i.e scope:true) when creating a directive, or is it more appropriate not to use it (i.e scope:false)? I grasp the distinction between scope types and their respective functionalities. However, I am uncertain about whic ...

Automate populating input fields with data

I need help with a form that has four input boxes. Is it possible to automatically fill the remaining three input boxes with the value entered in the first box when the user clicks a button using JavaScript? Or should I aim to prefill the textboxes with ...

Using a custom filter in AngularJS allows for seamless data filtering directly from the initial dataset

My goal is to implement a custom filter that will allow me to filter data based on a search word. The scope attribute gets populated in the controller's scope as shown below: naApp.controller('naCareNewTicketCtrl', ['$scope', &apo ...

When the Ionic app is relaunched from the side menu, the view fails to refresh

When I open my Side Menu, I initially see two options - scan barcode or search product. Once I choose one, the rest of the view is filled in dynamically. The issue arises when I try to go back to the Side Menu and reload the view to only display the origin ...

Fluid overlap of divs in Bootstrap framework

I am currently in the process of making style adjustments to a website at One specific change I've made is adding a top bar image. However, I've encountered an issue where the top bar graphic overlaps the navigation when the page is resized too ...

Managing code requiring document.title in Next.js with Static Site Generation (SSG)

Currently, I have 2 dynamic SSG pages located under /blog/[slug]. Within these pages, I am rendering a component using next/link. When I click on these links to navigate to another slug, I encounter an issue. The problem arises when I want to execute some ...