Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Use JavaScripts Spread Operator to Apply Style Objects Returned from CSS-in-JS Mixins

    Oleg IsonenOleg Isonen

    When defining CSS-in-JS style to use JavaScript Object Notation, mixins can no longer return strings as they can't be added to the object.

    In this lesson, you will convert the boxShadow and buttonSize mixins that return strings to return objects instead and spread those objects into the style object we are applying to an HTML Element.

    scssSCSS
    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 We have this css-in-js button. We start with using JavaScript object notation. We use a few variables here and there, but one part is missing. We are not using any mixins.

    00:12 Let's have a look at those mixins. This mixin is still using a template string. In order to use a mixin with object notation, we need to rewrite the mixin. The rewrite is pretty straightforward.

    00:24 Instead of returning a template string, we return an object now. T is our css properties, and the values are just variables. The same goes for button size mixin. Here is the object notation for button size mixin.

    00:38 We're still using a template string as a value here. The reason is this value is a compound value. In fact, this value represents four values. If I try to avoid a compound value, I will end up with something like this.

    00:52 There is a number of ways to optimize this, but most of them will end up with a custom syntax. For instance, we could so something like this. We invented a new padding property, which is called padding vertical, or padding horizontal. Now, we can use just one value.

    01:07 This pattern is what React Native is using, or we can do something like this. We have just introduced a new syntax for padding, which allows us to use object as a value, and top, bottom, left, right as a key.

    01:18 To me, this reads very explicit, but it's also more code. For now, we are going to focus on a string. Our mixins return objects, and we should be able to merge those declarations with this declaration.

    01:30 This is where spread operator becomes very handy. Spread operator is expressed by three dots, same like the Rest operator. Basically, what happens here is we call this button size function.

    01:42 This function returns an object, and then, we merge this object into this parent object. We can use console log in order to see the resulting shape of this object, and here is the result.

    Discuss

    Discuss