Search code examples
styled-components

Reuse a 'mixin' with Styled Components across different files?


How can I reuse a collection of styles with Styled Components across different files?

With SASS I can define and use a mixin like so:

@mixin section( $radius:4px ) {
  border-radius: $radius;
  background: white;
}

.box { @include section(); }

With Styled Components you can extend a style, but this means I would need to import that component into every page. This is pretty cumbersome compared to how variables are available everywhere with the ThemeProvider.

https://www.styled-components.com/docs/basics#extending-styles


Solution

  • You can create a string with multiple CSS rules and pass that to the ThemeProvider.

    const theme = {
      sectionMixin:
        'background: white; border-radius: 5px; border: 1px solid blue;',
    }
    
    
    <ThemeProvider theme={theme}>