Style HTML with JavaScript Template Strings and Objects in CSS-in-JS

Oleg Isonen
InstructorOleg Isonen
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 6 years ago

Sometimes it is convenient to be able to use both: template strings and objects. We will add a mixed mode to our CSS-in-JS function in just 2 lines of code and enable copy-pasting CSS from the dev tools.

Instructor: [00:00] Sometimes, it is convenient to use both object literals and template string for the css-in-js notation. For example, I could copy css directly from the dev tools and use it immediately in the code.

[00:13] Now, I inserted this css from the dev tools into a template string literal. Obviously, it doesn't work yet because we are expecting an object here. Let's make it work. Let's go back to css.js and make it accept a css string.

[00:30] This is the place where we iterate over the styles object, and we basically don't need to do this if our value is a string. If our declaration is of type string, let's just add our declaration to the css string.

[00:45] Otherwise, we are going to convert the object to a css string. Here we go. Our styles are defined using a template string. The button is green, and the result is correct.