Double ampersand trick in SASS with React

temmuz

Temmuz

Posted on December 25, 2019

Double ampersand trick in SASS with React

I learned a cool little trick last week while reviewing a PR and wanted to share it with everyone. This is pretty useful if you're using a library like emotion with React.

const StyledButton = styled(Button)`
  && {
    padding: 0;
  }
`

When I saw this, first I thought, they meant to style the Button component and redundantly included one ampersand (which i see some devs quite often do by mistake), the second one would then be a typo. But when I checked what it does in the Inspector, it was actually overwriting the default styling of the Button component like this:

.css1234--Button{
  // padding: 24px; -> overwritten
}
.css5678--StyledButton.css5678--StyledButton{
  padding: 0;
}

Repeating the class name with double ampersand will carry the priority above and overwrite the default styling coming from the Button component.
My mind is blown and I am bewailing the years of never having heard this trick and trying to overwrite everything with !important (when ordering the rules according to the cascade wasn't an option)

I'm really not sure how known this is but I thought it's super cool.
I hope you find that useful.

Please share your ampersand tricks with me via pm or comment below <3

💖 💪 🙅 🚩
temmuz
Temmuz

Posted on December 25, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related