Rewrite the styled-components in ReactJS with 60 lines of JavaScript code

Tram Ho

# alt text


styled-components is a library I really like when writing css for react, after a few days I have researched about its source, I decided to rewrite it to understand as much as possible, I feel like learning this repo so I wrote the article so I shared with everyone what I learned from it, in order to understand the code in my repo, I would say 2 new concepts to me and I must understand, if you guys If you already know, you can skip it ^^


If anyone knows the stylesheet in javascript, you can skip this paragraph. In the styled-components, it is used to store styles, each style tag has 1 sheet, each sheet has many rules, 1 rule corresponds to className and attached style, eg below illustrate how to add a rule to the sheet

Detailed link about it:

## Tagged templates The tagged templates I mentioned here are syntax that are commonly used in styled-components

The result is that we get the parameters like this

alt text

Detailed link about it:

## Embark on writing the library I will write the ComponentStyle class to handle the creation of the stylesheet and insert the css for the component

The code in the core.js file is probably the most ambiguous, I think to understand the most about your code, so I should clone this repo and run it then read here, it will be much easier to understand.

Finally, the code in the index.js file, is the file that this star will import it whenever using styled-components

And okay, you can import your fake styled-componets to use like a real library =)))) alt text You can go straight to the sandbox link to see and demo code


Hope everyone will find it interesting through my article, thank you guys for reading till here:)) Repo:

Share the news now

Source : Viblo