React Button with mui not changing colors correctly

755 Views Asked by At

I have code that looks similar to the following

import { Button ) from '@mui/material';
import { makestyles } from '@mui/styles';


const useStyles = makeStyles ({
    button: {
        cursor: "pointer",
        margin: "10px auto 20px auto",
        width: "80%",
        height: "50px",
        borderRadius: "5px",
        fontFamily: "Heiti SC",
        color: "#f7f7f7",
        backgroundColor: "#7dc241",
        "&:hover": {
            backgroundColor: "#679f35",
        }
    },
});

const form = () => {
    return (
        <form className={classes.form} onKeyDown={handleEnterDown} tabIndex="0">
            <Grid container spacing={2}>
                <Grid item xs={12} className={classes.formItem}>
                    <!-- email tag -->
                </Grid>
                <Grid item xs={12} className={classes.formItem}>
                    <!-- password tag -->
                </Grid>
                <Grid item xs={12} className={classes.formItem}>
                    <Button onClick={handleSubmit} className={classes.button}>
                        Log In
                    </Button>
                </Grid>
            </Grid>
        </form>
    )
}

The button renders correctly according to everything except colors. It renders the default react button colors even on hover. How do I fix this? Thanks in advance!

I tried changing the <Button> tag to the default html <button> tag and the colors were rendered correctly. But I need to know how to fix it for the mui <Button> tag

I tried this and its giving the same result

import { styled } from '@mui/material/styles';

const ColorButton = styled(Button)(({ theme }) => ({
  color: theme.palette.getContrastText(purple[500]),
  backgroundColor: purple[500],
  '&:hover': {
    backgroundColor: purple[700],
  },
}));
1

There are 1 best solutions below

0
On

I figured it out using the resource here. Essentially you have to target the specific button variant and change the color from there. The solution looks like this for the text variant:

const useStyles = makeStyles({
    button: {
        cursor: "pointer",
        margin: "10px auto 20px auto",
        width: "80%",
        height: "50px",
        borderRadius: "5px",
        fontFamily: "Heiti SC",
        "&.MuiButton-text": {
            color: "#f7f7f7",
            backgroundColor: "#7dc241",
            "&:hover": {
                backgroundColor: "#679f35",
            },
        },
    },
});

For other button variants, you can use these selectors

"&.MuiButton-root": {
    border: "2px black solid"
  },
  "&.MuiButton-text": {
    color: "grey"
  },
  "&.MuiButton-contained": {
    color: "yellow"
  },
  "&.MuiButton-outlined": {
    color: "brown"
  }