Search code examples
cssreactjssassstyled-componentsstyle-dictionary

Import style dictionary into styled components


I'm currently deciding which technologies to use in a project. I always liked sass, and the main reasons are the nesting of css and the possibility of creating dicionaty classes to hold all design information, such as pallet, margins, etc. Such as below:

$primary-color: #fff;
$seconady-color: #eee;

And then, in the actual .scss file I can import this dictionary and have easy access to pallete, thus achieving standartization and facilitating the creation of style sheets:

@import "dictionary.scss";

Styled components are a great thing, and I totally agree with their website stated advatanged. However, I do not like the idea of losing this dictionary functionality I have with sass. I know I can pass data to styled components from state and props, but that also means that, in some point, I will have to pass those props or state from somewhere. Like:

<Foo primaryColor="#fff" secondaryColor="#eee"/>

Is there a way I can conciliate this dictionary functionality I have with sass with styled components? Someway to import a dictionary.sass into my styledComponent.js file or even a .json or something. A way to import static pallet, fonts, margins data that is not React props or state.


Solution

  • You can declare the variables in plain Javascript in a file and import them where you style components.

    Dictionary file would look something like this:

    export const primaryColor = '#fff';
    export const seconadyColor = '#eee';
    

    Then interpolate them when you apply styling:

    import { primaryColor } from './variables.js';
    
    const Button = styled.button`
      border-radius: 3px;
      border: none;
      color: ${primaryColor};
    `
    

    You can also import Sass variables to JS: https://til.hashrocket.com/posts/sxbrscjuqu-share-scss-variables-with-javascript