Apply Multiple CSS-in-JS Arguments in a JavaScript Mixin Function with the Rest Operator

Oleg Isonen
InstructorOleg Isonen
Share this video with your friends

Social Share Links

Send Tweet

The rest operator in JavaScript allows us to 'collect' arguments dynamically in one variable similar to SCSS variable arguments

This is useful for CSS-in-JS when you have CSS properties like box-shadow that can attach multiple shadows to a single element. With the rest operator, you'll be able to add all the shadows you want to a single argument for use in a JavaScript CSS mixin function.

Instructor: [00:00] We have two buttons. One is written using SASS, and the other one is SCSS and JS. Let's have a look at this box-shadow and mixin.

[00:07] This mixin accepts a variable amount of shadows. You can pass just one shadow, or you can pass two, same like the native implementation of box-shadow in CSS.

[00:19] Let's have a look at the mixin itself. Here is the box-shadow mixin. We use here a SASS feature, which is called variable arguments. It allows us to just name one argument without knowing how many of them will be passed.

[00:32] To use it like a regular variable, this mixin allows us to generate vendor prefixes. Let's see how we can implement the same thing in JavaScript.

[00:42] Here we have our SCSS rule. Here are the box-shadow function/mixin call. Same like in SASS, we can pass one argument, two arguments, or basically an unlimited amount of arguments.

[00:55] Let's have a look at the mixin implementation itself. Here, we have our mixin function declaration. We assign this function to a box-shadow constant. We export this constant. Then we declare the function.

[01:07] First interesting thing about this function is the arguments. These three dots before the argument is called rest operator. Rest operator in JavaScript works exactly the same way like variable arguments in SASS.

[01:22] The interesting part is how we use the shadows array. JavaScript language has a feature called coercion. We just created the shadows array to demonstrate what happens within array inside of our mixin.

[01:36] Our mixin is a template string. If we use a variable inside of a template string which is not a string, JavaScript will always try to course this variable to a string.

[01:48] In our case, the result of a coercion is a string where red and green is comma-separated.