Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


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


    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.



    Become a Member to view code

    You must be a Pro 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
    orLog In




    Instructor: 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.

    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.

    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.

    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.

    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.

    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.

    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.

    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.

    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.