Using Javascript Variables with Styled Components

I use styled-components to build my components. All style properties that accept custom values ​​are reused in all my components (as it should be). With that in mind, I would like to use some kind of global variables so that updates apply to all components without the need to update each style separately.

Something like that:

// Variables.js var fontSizeMedium = 16px; // Section.js const Section = styled.section` font-size: ${fontSizeMedium}; `; // Button.js const Button = styled.button` font-size: ${fontSizeMedium}; `; // Label.js const Label = styled.span` font-size: ${fontSizeMedium}; `; 

I assume I misunderstood the syntax? Also, I know that global variables are not recommended on Javascript land, but in land design reusing styles between components is an absolute must. What are the trade-offs here?

+7
javascript styled-components
source share
2 answers

I finally figured it out, so here is how you can do it, at least if you use React.

You need to define the variables in one file and export them.

 // Variables.js export const FONTSIZE_5 = '20px'; 

Then you need to import these variables into each component file.

 // Button.js import * as palette from './Variables.js'; 

Then you can use variables in your stylized components, for example:

 const Button = styled.button` font-size: ${palette.FONTSIZE_5}; `; 
+10
source share

Wrapping the <ThemeProvider> application around your application can help:

https://www.styled-components.com/docs/advanced#theming

 const theme = { fontColour: 'purple' } render() { return ( <ThemeProvider theme={theme}> <MyApplication /> </ThemeProvider> ) } 

This will give all child styles access to the theme as follows:

 const MyApplication = styled.section` color: ${props => props.theme.fontColour} ` 

or

 const MyFancyButton = styled.button` background: ${props => props.theme.fontColour} ` 

Or access the topic through https://www.styled-components.com/docs/advanced#getting-the-theme-without-styled-components

+4
source share

All Articles