8
votes

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

2

2 Answers

9
votes

Just adding on to the answer by @Evanss

You can make the mixin a function (as in OP) by doing:

const theme = {
 sectionMixin: (radius) => `border-radius: ${radius};`
}

and then use it like:

const Button = styled.button`
 ${props => props.theme.sectionMixin('3px')}
`

or just:

const Button = styled.button`
 ${({ theme }) => theme.sectionMixin('3px')}
`
4
votes

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}>