user64209
user64209

Reputation: 107

Styled Components: Global Colors Style Sheet

I'm using styled components in my app. I wanna make a global style sheet to hold all my color variables. The API Docs recommend something like this

import { createGlobalStyle } from 'styled-components'

const GlobalStyle = createGlobalStyle`
  body {
    color: ${props => (props.whiteColor ? 'white' : 'black')};
  }
`

but i have a list of colors like this

export const COLORS = {
  navy: "#2F374B",
  green: "#1EB88D",
  white: "#FFFFFF",
  grey: "#222A3E",
  primary5: "#F4FBF9",
  danger: "#F13F4A",
};

and i dont think the body field can accept 'colors' or list of colors as a key. Any advice for setting this up?

Thanks in advance

Upvotes: 4

Views: 4325

Answers (1)

Cal Irvine
Cal Irvine

Reputation: 1144

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

You can use a theme provider and pass reusable properties there.

import { ThemeProvider } from 'styled-components'
import { COLORS } from './wherever'
const theme = {
  colors: COLORS
}

function App() {
  return <ThemeProvider theme={theme}><MainAppCode /></ThemeProvider>
}

When styling a component you can access the theme object as a prop:

const Button = styled.button`
  /* Color the border and text with theme */
  color: ${props => props.theme.colors.green};
`;

Anywhere you pass a function in the styled component template strings, the argument you get will be props, which contains your theme object.

Upvotes: 6

Related Questions