Access values from theme with React Styled System

521 views Asked by At

In my React project I am using Emotion and Styled System for my Design System and styling.

In theme.js I have some values (to create a responsive CSS Grid):

  template: {
    xs: {
      rows: 'auto',
      columns: 'auto',
    },
    sm: {
      rows: 'auto',
      columns: 'repeat(2,1fr)',
    },
    md: {
      rows: 'auto',
      columns: 'repeat(4,1fr)',
    },
    lg: {
      rows: 'auto',
      columns: 'repeat(6,1fr)',
    },
  },

How do I access those keys from my theme.js so I can use them like:

<Grid
  gridTemplateColumns={[
    theme.template.xs.columns,
    theme.template.sm.columns,
    theme.template.md.columns,
  ]}
  gridGap="30px"
>

I use already Emotion's ThemeProvider:

import { ThemeProvider } from 'emotion-theming';

<ThemeProvider theme={theme}>

How does this work with Styled System library and what is best practice here?

1

There are 1 answers

0
ljbc1994 On BEST ANSWER

You can use the useTheme hook in @emotion/react to get access to the theme object:

function Component(props) {
  const theme = useTheme()
  return (
   <Grid
     gridTemplateColumns={[
      theme.template.xs.columns,
      theme.template.sm.columns,
      theme.template.md.columns,
    ]}
   gridGap="30px"
  >
  )
}

References:

[1] Theming - UseTheme https://emotion.sh/docs/theming#usetheme