user349557
user349557

Reputation: 155

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

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?

Upvotes: 1

Views: 737

Answers (1)

Youssouf Oumar
Youssouf Oumar

Reputation: 46311

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>

Upvotes: 1

Related Questions