Understanding the benefits of CSS in JS

CSS is global in nature. So, if we use a CSS class name called container within a Header component, it would collide with another CSS class called container in a different CSS file if a page references both CSS files:

As the app grows and new team members join the development team, the risk of CSS changes impacting areas of the app we don't expect increases. We reduce this risk by being careful when naming and structuring our CSS by using something such as BEM.

Reusability in CSS is also a challenge. CSS custom properties give us the ability to use variables, but they are global variables and are not supported in IE. CSS preprocessors such as SCSS can, of course, help us with this. 

Ideally, we want to easily scope styles to a component. It would also be nice if local styles were defined in the component code, so that we can see and understand the structure, logic, and styling for a component without having to navigate through different files. This is exactly what CSS in JS libraries do, and Emotion is a popular CSS in the JS library. The syntax for defining the styling properties is exactly the same as defining properties in CSS, which is nice if we already know CSS well. We can even nest CSS properties in a similar manner to how we can do this in SCSS.

Later in this chapter, we'll see that Emotion will generate real CSS classes for the elements on the page to reference so that we still get the performance gain of CSS. Emotion just helps us scope the styles to specific components. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.123.173