Creating StyledComponents for inline styling

CSS-in-JS is a sometimes controversial topic. Before React, it was almost mandatory that you'd have a trio of sets of JS, HTML, and CSS separate files. When React introduced JSX, that was a shot against the trio, because we started placing HTML in the JS code. CSS-in-JS is the natural extension of that idea, because now we want to also include styling within the same JS files. 

A first reaction to this is: Isn't that just going back to inline styles? This is a valid question, but inline styles aren't just powerful enough. While you can manage lots of styling by inlining styles, the fact is that there are several features that aren't accessible in this way: keyframes animation, media queries, pseudo selectors, and more.

The idea of going with CSS-in-JS is writing styles by using JS, but then injecting those styles in a <style> tag within the DOM, so you'll have the full power of CSS for your code. Furthermore, this is also well-aligned with component-based approaches such as React's, because you manage to pack everything you need together in a properly encapsulated way instead of depending on global style files and having to deal with CSS's single namespace.

There are many packages that promote this way of styling, and out of those, we are going to pick styled-components, which is one of the best-regarded packages for CSS-in-JS styling. Its philosophy is interesting: instead of adding styles to components, you create components that incorporate those styles and use them everywhere. Let's start by seeing how to add this package to our code, and then move on to using it.

For the original talk on CSS-in-JS, by Christopher vjeux Chedeau, in which he gives the reasons for working with styling done in JS, see https://speakerdeck.com/vjeux/react-css-in-js.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset