I'm using styled-components to build my components. All style properties which accept custom values are reused throughout my components (as it should be). With that in mind, I'd like to use some sort of global variables so that updates will propagate to all components without needing to update each style individually.
Something like this:
// 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 guess I'm getting the syntax wrong though? Also, I know global variables are not recommended in Javascript land, but in design land reusing styles across components is an absolute must. What are the trade-offs here?
In SCSS, you can use variables and formulas for expressing colors, font sizes, widths and spacing variants. However, when you switch from SCSS to styled components, the syntax isn't valid anymore. Styled component files are CSS-in-JS, so they are actually JavaScript files.
To pass props to React components created with styled-components, we can interpolate functions into the string that creates the component. We create the ArrowStyled component with the styled. div tag. Then string that we pass into the tag has the rotate value set from a prop.
While you can reference global CSS variables within a styled-component, you can't reference sass variables nor global CSS variables containing strings.
I eventually figured this out, so here's how you can do it, at least if using 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 those variables into each component file.
// Button.js import * as palette from './Variables.js';
Then you can use the variables in your styled-components like this:
const Button = styled.button` font-size: ${palette.FONTSIZE_5}; `;
Wrapping a <ThemeProvider>
around your application may help:
https://www.styled-components.com/docs/advanced#theming
const theme = { fontColour: 'purple' } render() { return ( <ThemeProvider theme={theme}> <MyApplication /> </ThemeProvider> ) }
That will give all child styled-components access to the theme like so:
const MyApplication = styled.section` color: ${props => props.theme.fontColour} `
Or
const MyFancyButton = styled.button` background: ${props => props.theme.fontColour} `
Or access the theme via https://www.styled-components.com/docs/advanced#getting-the-theme-without-styled-components
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With