2

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.

1 Answers1

3

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

  • makeStyles method from MaterialUI is using generic type for defining what u can use from their Theme variables and, props type that u want to assign.

  • Theme type imported from : import { Theme } from "@material-ui/core";

  • makeStyles() returning theme value that u can use, the 'Theme' is the type definition for that theme value.

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. :)

Bona Ws
  • 356
  • 1
  • 10