Instead of having css (or equivalent) files, considering having styled components. There is serious value to taking this approach as it results in a much more contextualised styling system. Let us first take the following example that does not leverage this approach:
In file SomeComponent.tsx
|
1 2 |
const SomeComponent = () => <div className="test">Hello</div> |
in file styles.css
|
1 2 3 |
.test { color: purple; } |
notice that these two units of code are very decoupled, one could be deleted and the other would not be any the wiser until a user complains, and then it is too late! If we accidentally delete the styles from the css file we end up with visual regression, and if we delete the component we might not remember to remove the style, which results in redundant code.
Lets look at an example with Emotion styled component:
In file SomeComponent.tsx:
|
1 2 3 4 5 6 |
const Section = styled.div` color: green; ` const SomeComponent = () => <Section>Hello</section> |
Notice how the styles and the component are now coupled, everything is contextualised resulting in less risk and a better developer experience. Emotion even supports generics for complete prop type safety.
Another great feature of Emotion is automatic cross browser support, for example if you write this in your styled component:
|
1 |
mask-image: linear-gradient(black, transparent); |
and there is a required webkit variant, at runtime you will have:
|
1 2 |
-webkit-mask-image: linear-gradient(black, transparent); mask-image: linear-gradient(black, transparent); |