css-in-js
Tags: css, javascript
Published: 2021-02-21 17:33:30

## Introduction 
CSS-in-JS libraries have been gaining traction since component-based JavaScript frameworks appeared in front-end development.

#### Why we need css-in-js libraries ?
Due to the cascading nature of CSS (Cascading Style Sheets), stylesheets can load in any order and override each other in any combination.
Managing dependencies is another problem when it comes to styling SPAs (single-page application).

#### So
_ A well-designed CSS-in-JS library can solve all of this problems.
_ CSS-in-JS is, in fact, a JavaScript library that bundles each JavaScript component with all its belonging CSS rules and dependencies.
_ As a result, components can run independently, without relying on any external CSS file.

## CSS-in-JS Libraries :
there are two types of css-in-js libraries :

#### Framework-Specific libraries : 
libraries only work with a specific JavaScript framework.
_ex :_
 **Radium:** has been created for React apps.
 **Styled JSX:** only supports components written in JSX

_Framework-specific CSS-in-JS libraries:_ 
use the same syntax as the framework they support.

For instance:
 _Styled JSX_ uses template literals within the _JSX_ syntax to add CSS styles to components.

```
const Button = (props) => (
  <button className={ 'large' in props && 'large' }>
     { props.children }
     <style jsx>{`
        button {
          padding: 20px;
          background: #eee;
          color: #999
        }
        .large {
          padding: 50px
        }
     `}</style>
  </button>
)
 
/* Creates a regular button */
<Button>Hi</Button>
 
/* Creates a large button */
<Button large>Big</Button>
```

_Framework-agnostic CSS-in-JS libraries:_ 
can be used with any component-based frameworks .

for example :  _JSS_  &&  _Emotion_

> example using jss

```
/* Registers a Web Component with red background */
import { StyleSheet, css } from 'aphrodite';
 
const styles = StyleSheet.create({
    red: {
        backgroundColor: 'red'
    }
});
 
class App extends HTMLElement {
    attachedCallback() {
        this.innerHTML = `
            <div class="${css(styles.red)}">
                This is red.
            </div>
        `;
    }
}
 
document.registerElement('my-app', App);
```

### Unique Selectors vs. Inline Styles  
**css-in-js libraries use one of two techniques to handle scoping :**
* _unique selector:_ most CSS-in-JS libraries such as _JSS_, _Emotion_, and _Styled Components_ automatically generate a unique selector for each component.
In this technique library generates a unique selector such as a unique class that won’t cause any CSS specificity problems.

_**but**_ this makes the source code doesn’t look very pretty.

* _inline styles:_ some CSS-in-JS libraries such as Radium add inline CSS on the fly to the HTML instead of generating unique classes.

_adv of using inline style library:_
1. lead to more readable HTML code.
2. better performance.
3. source order independence.


## Advantages of CSS-in-JS
* ##### Local Scoping:
__ By default, CSS doesn’t allow local scoping. Each style rule has a global scope. So as a result styles can override each other in surprising ways.
__ CSS-in-JS libraries solve this by automating scoping, which leads to a high level of predictability.

* ##### Encapsulation:
__ Encapsulation facilitates maintenance and eliminates errors, as you can modify all component-related code in the same place, without having to worry about unexpectedly changing other parts of the application. 

* ##### Portability:
__ As components include all the source code, styles, and logic, you can securely move them around.

* ##### Re-usability:
__ Components are reusable, so you only have to write them once, then you can run them everywhere.

* ##### Dynamic Functionality:
__ As CSS-in-JS is essentially JavaScript code, you can apply complex logic to your style rules, such as loops, conditionals, variables, and more.


## Disadvantages of CSS-in-JS
_Although CSS-in-JS libraries allow you to build component-based applications in a logical and efficient manner, they also have some characteristics that might make you wary of them._

* ##### Extra Layer of Complexity:
__ using css-in-js library adds an extra layer to your front-end stack, which can sometimes be unnecessary.

* ##### Code Readability:
__ Automatically generated selectors significantly worsen code readability.

## References:
* [jss](https://cssinjs.org/from-sass-to-cssinjs)
* [An Introduction to CSS-in-JS](https://webdesign.tutsplus.com/articles/an-introduction-to-css-in-js-examples-pros-and-cons--cms-33574)
* [Set CSS styles with javascript](https://dev.to/karataev/set-css-styles-with-javascript-3nl5)
* [CSS-in-JS](https://css-tricks.com/bridging-the-gap-between-css-and-javascript-css-in-js/)
* [Understanding CSS-in-JS](https://www.telerik.com/blogs/understanding-css-in-js)