Using Javascript Variables with styled-components

colmtuite picture colmtuite · Apr 19, 2017 · Viewed 20.2k times · Source

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?

Answer

Ricardinho picture Ricardinho · Aug 15, 2017

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