Search code examples
cssreactjsstyled-components

styled-components local variable


Coming from SCSS (SASS)

What would be the appropriate Styled-Components implementation of the below SCSS code?

SCSS:

.circle{
  $size: 16px;  // <-- SCSS FTW. use such a trick in styled-components

  height: $size;
  width: $size;
  .. rest of properties...
}

Currently the styled-component (Circle) looks like this:

...lots of other styled exports

export const Circle = styled.div`
  height: 16px;
  width: 16px;
  background: red;
  border-radius: 50%;
`

...lots of other styled exports

Problem is, I want to keep that "meaningless" size variable in the same context where it's consumed (just like in SCSS) because nothing else cares or will ever care about it. I don't think dumping a variable somewhere and then using it with '${size}' is a "clean" way. such tactics are petty and promote messy code-base.


Solution

  • I have devised a neat trick to encapsulate variables only for a specific scope:

    styled.h1(({size='4em', color='lime'}) => `
      font-size: ${size};
      color: ${color};
      text-align: center;
    `)
    

    I've written a Medium post in the past which breaks down the explenation of this method