Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 964
user64209 Avatar asked Nov 01 '25 17:11

user64209


1 Answers

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.

like image 82
Cal Irvine Avatar answered Nov 04 '25 05:11

Cal Irvine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!