💄 glamorous is a lightweight library for CSS-in-JS with a simple API that’s similar to styled-components’ and that makes use of glamor under the hood. Two of the main differences compared to styled-components is the use of JavaScript object literals and an additional API that allows to use DOM elements directly without creating additional named components.
Let’s go over how to use glamorous to give our components some style.
To get started, you’ll need a few packages: glamorous, glamor and prop-types:
Then, all you have to do to start using it is to import the default export from the library:
You create a glamorous component and give it some style using the name of any DOM element and providing an object literal with CSS property names (camel-cased) and values:
You can access props passed-in to a glamorous component using a callback function as the second argument when creating the component:
Media queries using glamorous is just as easy really:
And likewise for pseudo-elements and pseudo-classes:
Notice the use of double quotes inside the single quotes for the :before pseudo-element. That syntax is important for the pseudo-element to work correctly.
For simpler and smaller components, you can also use an alternative API where you import components that correspond to a specific DOM element and use them directly. This way you avoid having to come up with a bunch of names for your glamorous components:
glamorous is smart enough to distinguish between native element attributes and style props. With the above example, the card-title class will be added to the element as an additional class on top of the one generated by glamorous for the border-bottom style.
You can make use of glamorous’ ThemeProvider component to provide theme information that will be made available to all the components down the tree.
For example, here’s how you would provide a theme from the App component:
The button’s onClick handler toggles between our two themes and the ThemeProvider’s children components will automatically have access to the theme data.
You can access the theme from the props passed-in to the callback when creating a glamorous component:
glamorous doesn’t bother itself with global styling and instead you can revert to glamor’s css.global to inject some global styles into your apps:
🤓 And that’s it for our little intro to glamorous. Refer to the official docs for more advanced use cases.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!