Autoplay

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

    Oleg IsonenOleg Isonen

    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.

    cssCSS
    javascriptJavaScript
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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.

    Discuss

    Discuss