CSS-in-JS - Moving Styles Into Javascript
Explore the CSS-in-JS approach to React styling that embeds CSS within JavaScript to create isolated, reusable components. Understand how styled-components and other libraries enable writing CSS in template literals, offering benefits like automatic vendor prefixing, theming support, and reduced CSS conflicts.
What is CSS-in-JS?
We already mentioned in the introduction that CSS-in-JS is a bit of a hotly debated topic. Opponents say that users of CSS-in-JS simply do not understand the cascade to write scalable CSS. Proponents, on the other hand, explain that the cascade is not the main reason for choosing CSS-in-JS but argue that a safer way is needed to write highly isolated components. However, there could be room and reasons for both. CSS-in-JS certainly has a reason to exist. But what even is CSS-in-JS?
The CSS-in-JS approach mandates that the styles that are commonly found in CSS files are now moved into JavaScript. As was already the case in CSS modules, the primary goal is to create highly isolated components free of conflict, making them easy to reuse throughout the application. However, as opposed to CSS modules, the styling in CSS-in-JS happens entirely in JavaScript. The syntax is very similar, and it mostly feels like you’re writing regular CSS.
CSS-in-JS is the umbrella term for the concept, whereas ...