1.0.9 • Published 4 years ago

styled-components-theming v1.0.9

Weekly downloads
1
License
MIT
Repository
github
Last release
4 years ago

styled-components-theming

Ease theming.

While working with styled-components, I realized two problems keep happening:

  • I have to switch between themes (dark, light, ...)
  • I usually have the following code to get theme values:
const Item = styled.div`
  color: ${({theme}) => theme.textColor};
  background-color: ${({theme}) => theme.pageColor};
  padding-top: ${({theme}) => theme.spacings[2]};
  padding-bottom: ${({theme}) => theme.spacings[2]};
`;

That's why I've decided to group some repetitive code to a package called styled-components-theming.

Setup

Install the packages:

yarn add styled-components styled-components-theming

Firstly, we need to create the theme object:

import {createTheme} from 'styled-components-theming';

const theme = createTheme(
  {
    dark: {
      textColor: 'white',
      pageColor: 'black',
    },
    light: {
      textColor: 'black',
      pageColor: 'white',
    },
  },
  {
    common: {
      spacings: [0, '8px', '16px'],
    },
  }
);

This factory function createTheme has two parameters:

  • versions: an object with its keys stand for theme versions (light, dark, ...). Each of the children is a typical theme object
  • config: an object which has only one recognizable key:
    • common: an object which will be merged to each of the given theme versions. This is just there to minimize duplication.

Next, we must wrap the app with ThemeProvider (don't forget to pass the theme above):

import {ThemeProvider} from 'styled-components-theming';

const App = () => {
  return (
    <ThemeProvider theme={theme}>
      <HomePage />
    </ThemeProvider>
  );
};

Use cases

Convert the old theme accessing code to this:

import {getThemeValue as $} from 'styled-components-theming';

const Item = styled.div`
  color: ${$('textColor')};
  background-color: ${$('pageColor')};
  padding-top: ${$('spacings[2]')};
  padding-bottom: ${$('spacings[2]')};
`;

If you need to switch between themes, you can use ThemeContext:

import {ThemeContext} from 'styled-components-theming';

const HomePage = () => {
  const {version, setVersion} = useContext(ThemeContext);

  return (
    <div>

      <button
        onClick={() =>
          version === 'dark' ? setVersion('light') : setVersion('dark')
        }
      >
        Switch theme
      </button>
    </div>
  );
};

By default, this library supports saving the current theme version to localStorage under the key styled-components-theming-key.

1.0.9

4 years ago

1.0.8

4 years ago

1.0.7

4 years ago

1.0.6

4 years ago

1.0.5

4 years ago

1.0.4

4 years ago

1.0.3

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago