Home > Net >  How to use material ui sx props with a styles object?
How to use material ui sx props with a styles object?

Time:06-12

I have a styles object that would look like this:

styles = {
  color: "#333",
  fontSize: "16px",
};

I could apply styles to a Material UI component like below and it would work.

<Button sx={styles}>Example</Button>;

However, what if the Button component already had custom styles? How would I push my styles object then? For example, in this case:

<Button
  sx={{
    backgroundColor: "red",
    fontWeight: "700",
  }}
>
  Example
</Button>;

How would I add the styles object without overwriting the sx prop?

CodePudding user response:

You could use the Spread syntax, like below. If you wanna know more about it, you can read on MDN's documentation.

What it's doing, in my words, is that it removes styles object's {}, and add it into the final object.

styles = {
  color: "#333",
  fontSize: "16px",
};
<Button
  sx={{
    backgroundColor: "red",
    fontWeight: "700",
    ...styles,
  }}
>
  Example
</Button>
  • Related