An Introduction to CSS in JS: Thorough Analysis & Advantages
What is CSS in JS?
Advantages of CSS in JS:
Since style rules have a global scope, it applies to the entire application. Though we have now started modularizing CSS using methods like BEM, PostCSS, etc., CSS in JS libraries provides a great way of automatic local scoping, giving high predictability over the CSS code.
By including CSS in JS files, we can render the styles dynamically based on the requirement and take advantage of native JS syntax features. This simplifies implementing a complicated design as we can use conditionals, state-based rendering, loops, etc., to apply the styles.
Generates Unique Selectors:
These libraries apply the styles to an element by adding a unique dynamic className to the element. In this way, we can eliminate the CSS specificity problems.
One of the popular framework-agnostic modules to use CSS in JS is the aphrodite npm module.
In this blog, we will look at a small illustration of how aphrodite works.
To begin with, let us create a simple react button component.
This button uses inline styles defined in style objects. On inspecting the element in the console, we can see that styles are added in line with the style attribute in the button element.
The code will look as follows when converting the same to use aphrodite:
We wrap our styles inside a call to StyleSheet. We create a method and define an object key button to represent the styles.
Instead of assigning to style, we use className, and we call the CSS method passing in styles.button
On running the program, the output looks the same as before. But, on inspecting the element, we can note that a class is added to the button, and also a style tag is added which contains all the styles defined by us.
Aphrodite parses our code, turning it into CSS and injects it into the DOM. It also uses the object key button to generate a unique class name (button_leq016), which is passed as the className attribute.
Blog Authored by: Shiny Matilda Christina Joseph and Nandhini Meenal Balasubramanian