DEV Community

Temmuz
Temmuz

Posted on

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

Top comments (7)

Collapse
 
rodmartinezmedina profile image
Rodrigo Martinez Medina

Great article, to spread a useful functionality.

Works also with styled components!
It's in the official documentation for styled components for instance with some example.
styled-components.com/docs/basics#...

Collapse
 
temmuz profile image
Temmuz

Thanks for pointing out. Maybe I should read the documentation better next time :P

Collapse
 
rodmartinezmedina profile image
Rodrigo Martinez Medina

Man, you shared useful info with people and found it by yourself. More than cool enough!
:)

Collapse
 
dance2die profile image
Sung M. Kim • Edited

Nice tip there, Temmuz.

Man, I never thought that'd be the case.

Do you have a link to a documentation on how that works by chance?

Collapse
 
temmuz profile image
Temmuz • Edited

I didn't find anything on that matter really. I get why double ampersand doubles the classname but the thing about the priority is something I've only come to the conclusion of. Nothing written on that afaik

Collapse
 
dance2die profile image
Sung M. Kim

You gotta do a PR for this on the emotion repo :)

Collapse
 
5456qwe profile image
1214586

yo das really nais stuff my friend