Emotion: Global style variables with emotion?

Created on 6 Apr 2018  路  3Comments  路  Source: emotion-js/emotion

One of the only remaining obstacles before dropping my SASS setup for emotion is the use of global variables. In SASS I have a theme.scss which I import into each component.scss, and which contains style variables which I then use. Can a similar approach be achieved with emotion?

An example of a variable I might want to use is a standard size variable, which I would then consistently use in various components for padding, margin and any other cases.

injectGlobal isn't quite that, unless I could define global variables there?

Most helpful comment

You can define your variables in JavaScript like you define any other variables and use them in your styles. For example, you could have a theme.js file and import what you need from it in component files.

// theme.js

export const colors = {...someColors}
// component.js
import { css } from 'emotion'
import { colors } from './theme.js'

const cls = css`
  color: ${colors.pink}
`

All 3 comments

You can define your variables in JavaScript like you define any other variables and use them in your styles. For example, you could have a theme.js file and import what you need from it in component files.

// theme.js

export const colors = {...someColors}
// component.js
import { css } from 'emotion'
import { colors } from './theme.js'

const cls = css`
  color: ${colors.pink}
`

Thanks for the explanation and illustration, that should do it.

Having said that, when thinking about theming globally, it would result in a kind of a split approach - I define app font and things through the ThemeProvider, and style variables via the theme.js?

@artooras I have the same issue. But found the solution. css returns a class so it cannot be used with ThemeProvider. So you'd need to import default values for themes.js if you're using css & if you're using anything else you can use props.theme

Was this page helpful?
0 / 5 - 0 ratings