1

I have been implementing MUI (v5) on a create-React-App with typescript. I have a customed-theme and all.

I want to create a MyButton Component that takes a buttonType props (typeof string) which refer to my theme.palette and pass it to the MuiButton it is build upon to define its color.

I tried several approaches.

  • The color props from the MUIButton seem not to accept any variable even if their type is matching the enum it is defined by. doc here
  • The classes are not applied unless !important is specified doc here
  • Passing buttonType into the useStyle return an error. doc here

here the code :

in App.tsx file :

function App() {
    return (
        <div className="App">
            <h1>My customized buttons</h1>
            <div className="buttonContainer">
                <MyButton buttonType={'primary'}/>
                <MyButton buttonType={'secondary'}/>
                <MyButton buttonType={'warning'}/>
                <MyButton buttonType={'error'}/>
                <MyButton buttonType={'success'}/>

            </div>
        </div>
    );
}

in MyButton.tsx file :

import MuiButton, {ButtonProps as MuiButtonProps} from '@mui/material/Button';
import {makeStyles} from '@material-ui/core/styles';

const useStyles: any = makeStyles((theme: Theme) => ({
    root: {
        border: '3px solid red',
        borderRadius: 5,
        padding: theme.spacing(1, 2),
        margin: theme.spacing(2),
    },
}));

const useButtonStyles: any = makeStyles((theme: Theme) => ({
    root: {
        border: '3px solid blue',
        backgroundColor: (buttonType: string )=>buttonType,      
    },
}));


function MyButton({buttonType = 'primary'}: MyButtonProps) {
    const classes = useStyles();
    const buttonClasses = useStyles(buttonType);
...

return(

       <div>
            <MuiButton classes={classes}>Button only makeStyle</MuiButton>

            <MuiButton classes={classes} color={'primary' === buttonType ? 'primary' : buttonType}>Button {buttonType}</MuiButton>

            <MuiButton classes={buttonClasses}> Color defined in MakeStyle with {buttonType} </MuiButton>

            {/*color passed as string get theme.palette colors without issue */}
            {/*<Button color="error">Button Error</Button>*/}
            {/*<Button color="warning">Button warning</Button>*/}
            {/*<Button color="success">Button success</Button>*/}
       </div>
);
}

export default MyButton;

interface MyButtonProps {
    buttonType: 'inherit' | 'primary' | 'secondary' | 'success' | 'error' | 'info' | 'warning' | string,
}


enter image description here

Lyly
  • 43
  • 7

1 Answers1

1

probably you need to extend the MyButtonProps from MuiButtonProps before setting it as your custom button component props type.

interface MyButtonProps extends MuiButtonProps {
    buttonType: 'inherit' | 'primary' | 'secondary' | 'success' | 'error' | 'info' | 'warning' | string,
}
timgcarlson
  • 3,017
  • 25
  • 52
Mohsen
  • 333
  • 2
  • 11