Tips for applying a custom design to your MUI V5 styled component

How do I customize the style of a button component in MUI V5? I've been trying to combine old methods with the new version, but it's not working as expected.

import { Button } from "@mui/material";
import { styled } from "@mui/material/styles";
import React from "react";

const StyledButton = styled(Button)(({ theme }) => ({
  root: {
    minWidth: 0,
    margin: theme.spacing(0.5),
  },
  secondary: {
    backgroundColor: theme.palette.secondary.light,
      "& .MuiButton-label": {
        color: theme.palette.secondary.main,
      },
  },
  primary: {
    backgroundColor: theme.palette.primary.light,
     "& .MuiButton-label": {
       color: theme.palette.primary.main,
     },
   },
}));

export default function CustomButton(props) {
  const { color, children, onClick } = props;

  return (
    <Button
        className={`${StyledButton["root"]} ${StyledButton[color]}`}
        onClick={onClick}
    >
      {children}
    </Button>
  );
}

Now to use this Button with a "secondary" color:

import CustomButton from "./CustomButton";
import { Close } from "@mui/icons-material";
export default function Header() {
    return (
        <CustomButton color="secondary">
            <Close />
        </CustomButton>  
     
    )
}

Answer №1

If you were trying to update your code from using makeStyles/useStyles to styled, it's important to note that they are quite different. Unlike makeStyles, styled does not generate multiple CSS classes like StyledButton["root"] and StyledButton[color], which will be undefined. Instead, styled generates a single CSS class that is then passed in the className prop to the wrapped component (e.g. Button). With styled, you can use props (like the color prop) to dynamically generate styles within the generated CSS class.

Here is an example that I have provided to help achieve the effect your code was aiming for. The example doesn't utilize MuiButton-label as this class does not exist in version 5 of the library. Additional changes may be necessary when passing the color prop through to the Button.

import Button from "@mui/material/Button";
import { styled } from "@mui/material/styles";

const StyledButton = styled(Button)(({ theme, color }) => ({
  minWidth: 0,
  margin: theme.spacing(0.5),
  backgroundColor: color ? theme.palette[color].light : undefined
}));

export default StyledButton;

https://codesandbox.io/s/styled-button-j7e06?fontsize=14&hidenavigation=1&theme=dark

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

Whenever I try to make my links responsive, they don't seem to work as intended

This is the HTML snippet <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> ...

When the enter key is pressed in a contenteditable div, line breaks are disregarded

Is there a way to ensure that when the return key is pressed to start a new line for a post, the output actually starts on a new line? I've been having trouble with this and would like to know the most common solution. Check out the demo below for te ...

How to efficiently search MongoDB for existing records and group them by unique array values

My dataset is structured like this: { "_id" : 1, "category" : [ { "name": "category1" }, { "name": "category2" } ], "event": [ { type: "house" ...

The input came to a sudden and unexpected end, we were looking for the }

Is there a solution to the error that occurs when attempting to execute npx flow? ...

Having trouble accessing certain pages in a React .NET application without a direct link?

I developed a React application with .NET using Visual Studio, and everything runs smoothly when tested locally. After deploying the app to Azure App Service, the home page functions properly. However, I encounter a 404 Not Found error when attempting to a ...

Is it possible to populate an empty list of objects within the Page_Load scope after the page has finished loading?

I am facing a challenge where I need to populate the list var docfiles = new List<string>(); with file names uploaded by the user using dropzone js. However, the list remains empty because when the page loads for the first time, httpRequest.Files.C ...

A two-column bootstrap design with zero padding or gaps

This is the layout I am aiming for: Below is the code I currently have: <div class="row "> <div class="col-lg-6 row-eq-height push-right"> <img src="1.jpg" class="img-responsive"> </div> <d ...

Connecting JavaScript and jQuery scripts

Help needed! I am a beginner in the world of jQuery and JS. Unfortunately, my JS/jQuery code is not running and I can't figure out why. Can someone please take a look at my HTML and guide me on what might be causing the issue? Do I need to add some ad ...

What is the best way to create grid designs using less in bootstrap?

When using Bootstrap without a preprocessor, we include classes directly into our opening tags like this: <div id="El" class="col-md-1"></div> Personally, I usually work with Bourbon Neat and Sass. With Sass, I can import mixins in the rules ...

What issues could arise from utilizing PHP for generating variables within my CSS file?

One major limitation of CSS is the absence of variables. It would be beneficial to have the ability to use variables for controlling things like the location of imported CSS and color schemes within a design. An alternative solution could involve using a ...

Perform the same actions on every element within the ul li

I'm facing an issue with my unordered list, where each list item contains a span element with an image inside. My goal is to set the background-image of each span to be the same as the image it contains, while also setting the opacity of the image to ...

Learn how to access nested arrays within an array in React using TypeScript without having to manually specify the type of ID

interface UserInformation { id:number; question: string; updated_at: string; deleted_at: string; old_question_id: string; horizontal: number; type_id: number; solving_explanation:string; ...

Create a function that triggers a fade-out effect on one button when another button is clicked

Hello everyone! I'm still getting the hang of things around here so please be kind. I need some assistance with my weather app project. Specifically, I've created two buttons and I want to make it so that when one is clicked, the other fades to g ...

Having trouble deploying a React app on Digital Ocean? If your application is getting stuck at the 'starting development server' stage, here’s

After deploying my app on the Digital Ocean App platform and successfully connecting it to my GitHub page, I encountered an issue when trying to access the live site. Upon opening the site, I received a 504 error and upon checking the logs on the App plat ...

React encountering a 400 Bad Request Error with Axios

I've gone through all the posts about Axios 400 bad request, but I still can't find a solution. In my useEffect function, I first fetch data from my API and later on, depending on certain conditions, I may need to make a POST request back to the ...

The functionality in the React Native code that uploads images to an S3 bucket is currently failing to initiate the network request

I have been using a redux-observable epic to upload images to my AWS S3 bucket through react-native-aws3. It has been functioning smoothly for quite some time. However, recently it seems to have stopped entering the .map and .catch blocks of code. I suspec ...

The jQuery date picker is showing an error with the function daySettings[2].replace, indicating that

Encountering a problem with the jQuery version I am using: <script src="js/Common/jquery-2.1.1.min.js" type="text/javascript"></script> <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script> The code I have writte ...

Is there anyone available who can assist me in removing records from my Sequelize database?

I attempted to implement the code snippet below after coming across it on a popular platform, but for some reason, it doesn't seem to be functioning as expected. Posts.delete({ where: { createdAt: { isAfter: "2016-09-11" } } }) My goal is to remove ...

When using useEffect to mimic componentWillUnmount, the updated state is not returned

My goal is to have a functional component with initialized state using useState, which can be updated through an input field. However, upon unmounting the component, I want to log the current state instead of the initial one. In this hypothetical scenario ...

PhantomJs is only providing partial responses

I have been attempting to retrieve a response from the following URL using PhantomJS:- https://www.trivago.com/api/v1/bin/accommodation/2891353/deals?iPathId=34812&iRoomType=1&aRooms=&aDateRange%5Barr%5D=2017-05-24&aDateRange%5Bdep%5D=2017 ...