Become a member
to unlock all features

Level Up!

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


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


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

    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.

    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.

    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.

    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.

    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.

    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.

    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.