Use JavaScript Functions as Mixin Directives for CSS-in-JS Style Declarations

    Oleg IsonenOleg Isonen

    Mixins are reusable pieces of code that allow you to group CSS declarations together. If we want to add another button with different button sizes, we can simply pass different arguments to a button size mixin that will format our the variables passed in into valid CSS.

    You will learn how to use JavaScript functions as an alternative to @mixin directive. Also we will learn how a function can become a CSS mixin.



    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


    Instructor: 00:00 We have two buttons. One is written in Sass, the other one is using css-in-js. Let's have a look at the Sass implementation. We are using include directive here, and we are using a mixin.

    00:13 Button size mixin accepts padding, font size and border radius. Let's have a look at this mixin. Button size mixin uses the arguments in order to implement padding, font size and border radius.

    00:31 Why are we actually using a mixin in here? Mixin is a reusable piece of code. If we want to add another button with a different button size, we can simply pass different arguments to the button size mixin.

    00:46 For instance, we could create a button small and pass different sizes to this button. Let's have a look at the css-in-js button. As usually, we import variables, and we also import mixins.

    01:00 We declare css template string, and this is how we use the mixin. In reality, JavaScript, as a language, has no mixins. A function can do everything a mixin can do. We call a button size function we imported previously, we pass the arguments same way we did in Sass, and we render the scss.

    01:24 Let's have a look at the mixin function. We use an arrow function expression in order to create our function. Basically, we declare a constant, and we assign an arrow function to this constant.

    01:38 In the braces, we describe the arguments, and after the arrow, we describe the return value. The return value in this case is a JavaScript template string. In order to be able to call our function a mixin, we need to return scss declaration block.

    01:55 We declare some properties, and we use arguments inside of interpolations. This declaration block can be mixed in into some other declaration block. What we saw inside of the mixin, we'll use the variables we pass in here, and will be inserted in this declaration block.