qweezz
qweezz

Reputation: 804

How to pass custom props to Material-UI component using makeStyles/withStyles?

How can I pass a custom props to MUI component? Let's say I want pass customProps='red' which changes the background color of a component?

In my case I need to add a different background color for a button and I want to add something like this:

<SubmitButton
  variant={"outlined"}
  customBackground={'red'} // this prop
>
  Submit
</SubmitButton>

Should I use makeStyles?

Here's the codesandbox.

Upvotes: 2

Views: 1635

Answers (1)

NearHuscarl
NearHuscarl

Reputation: 81340

In your styles defined with withStyles

root: {
  backgroundColor: (props) => props.customBackground
  {...}
},

Then in the component created by withStyles HOC:

<SubmitButton customBackground="red"

If you want to set a group of style properties, you can pass a callback that returns a style object instead of a value (docs):

root: ({ mode }) => ({
  ...(mode === "dark" && {
    backgroundColor: "black",
    color: "lightgray",
    "&:hover": {
      backgroundColor: "darkblue"
    }
  }),
  ...(mode === "light" && {
    backgroundColor: "white",
    color: "black",
    "&:hover": {
      backgroundColor: "lightblue"
    }
  }),
})

Then pass the prop in your custom component to apply dynamic styles:

<SubmitButton mode="light">light</SubmitButton>
<SubmitButton mode="dark">dark</SubmitButton>

Should I use makeStyles?

makeStyles and withStyles are the same except that makeStyles returns a hook which cannot be used in a class component. If you use functional component, you should use makeStyles because it's more pluggable (easier to add or remove styles).

Codesandbox Demo

Upvotes: 3

Related Questions