reactjstypescriptmaterial-uimakestyles

makeStyles with TypeScript - pass props to make styles explanation


I'm using Material-UI makeStyles function with TypeScript

I found the solution here on how to do that and it is working:

export interface StyleProps {
  md?: any;
}

const useStyles = makeStyles<Theme, StyleProps>({
  button: {
    width: ({ md }) => md && '50%',
  }
});

export default useStyles;

But I'm trying to understand how things work.

I don't understand the <Theme, StyleProps> part. I looked at all solutions on StackOverflow regarding this, no one explained it.

Could someone please clarify it?

Thanks.


Solution

  • Here is my simple explaination about the <Theme, StyleProps>

    Code Example :

    #1 makeStyles using only the theme value :

    const useStyles = makeStyles<Theme>((theme) => ({
      button: {
        background: theme.palette.background.paper,
        color: theme.palette.success.light
      }
    }));
    

    #2 makeStyles using theme value & your props :

    const useStyles = makeStyles<Theme, StyleProps>((theme) => ({
      button: {
        background: theme.palette.background.paper,
        color: theme.palette.success.light,
        width: ({ md }) => "50%"
      }
    }));
    

    #3 makeStyles using only your props :

    const useStyles = makeStyles<any /* <-- it doesn't matter what type u define here, because u doesn't use theme value*/, StyleProps>({
         button: {
           width: ({ md }) => "50%",
           background: "grey"
         }
        });
    

    Hope this answer can help. :)