Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 649
Evanss Avatar asked May 08 '18 08:05

Evanss


2 Answers

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')}
`
like image 53
Jamie Kudla Avatar answered Sep 27 '22 20:09

Jamie Kudla


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}>
like image 43
Evanss Avatar answered Sep 27 '22 20:09

Evanss