What is CSS in JS?

Tram Ho

CSS in JS or CSS-in-JS is a term that describes writing CSS style codes in JS code, ie writing in .js , .jsx files instead of writing CSS code in .css files as usual.

When was CSS in JS born?

CSS-in-JS came into being when websites became more and more complex and it became difficult to maintain all the CSS of the entire website system (large code base).

Since all CSS will be in the same global scope document (or global scope selectors) causing many conflicts (when class names, ids are the same) and overriding CSS becomes more difficult (overriding multiple classes, using !important ! , …) .

In addition, the growing trend of component-based development (or component driven development) with React makes it even more imperative to style each component (component).

How did CSS-in-JS help with these problems?

CSS-in-JS will extract CSS by component instead of by document like CSS.

styled-components is the most commonly used CSS-in-JS library. There are also Aphrodite , Radium , Glamorous , JSS

An example with the Styled Component library ( styled-components ):

Create a default Text that will receive a p tag, with a font size of 16px.

and pass the h2 tag to the “as” attribute for Text to use:

Then the CSS code will automatically create a unique class and be attached to the DOM as follows:

Advantages of using CSS-in-JS

→ More concise and consistent code

→ Reduce CSS conflicts

→ Dynamic CSS with props

→ Style inheritance

→ SASS syntax makes styling easy with pseudo element and pseudo class

→ Easily change themes with ThemeContext

→ Automatically create prefix for CSS class, not afraid of overlapping

→ Can write unit tests for CSS

Cons of using CSS-in-JS

→ Will not be suitable for those who do not know JS

→ It takes time to get used to the library, making it difficult for newcomers

→ Difficult to debug by class name

→ Performance is not as good as CSS, due to using more style tags, heavier code base

Above are a few summary notes I learned about CSS-in-JS.

For me, if the project is small, and working with you guys who do not have much experience in JS, OOP, … then I will choose traditional CSS (or SASS – still dynamic) because it will be more accessible to you.

For medium and large projects, high inheritance, many components, more experienced devs, I will choose CSS-in-JS libraries like styled-components.

What do you think about CSS-in-JS? If given the option, would you use styled-components or traditional CSS to style your React app?

The original article is in my personal blog, please visit.

Share the news now

Source : Viblo