CS代写 <> CSS in JS

<> CSS in JS
Presented by

Copyright By PowCoder代写 加微信 powcoder

What is CSS’s major problem when used with React?

CSS Selectors all exist in the same global scope.

FirstComponent.js
SecondComponent.js SecondComponent.css

Encapsulation
Encapsulation is an important property of maintainability in a codebase. Properly encapsulated components will not have any implicit dependencies on each other.
In other words, the component won’t have access to things it shouldn’t know about. If we do this right, our code is decoupled.
CSS imports are global, which breaks decoupling, because a component will have access to styles that are not within its own scope.

This means…
We can never truly have confidence that our components do what they say they do.
Every time I add a class name to a div, I have to worry that in some my class name has been defined in someone else’s CSS file.
Imagine being in a group project, and two team members both write a component. For some reason whenever you add a class name to your component, it turns red, starts flashing and moves to the left side of the screen.

How did we get here?
CSS was invented for HTML files and single file web pages. It doesn’t really translate to our component-based way of working.

CSS Modules

Stands for Block, Element, Modifier. Predates React by a number of years.
Is a Naming Convention. No special technology here, just a way to name your components so that they don’t tread on each other’s toes.
The history of BEM began in 2005. Back then, from the frontender perspective, a typical project was a set of static HTML pages.

A Block is a standalone name, meaningful on its own, like button.