Create a CSS mixin in React using styled-components

Joe Previte
InstructorJoe Previte

Share this video with your friends

Send Tweet
Published 3 years ago
Updated 3 years ago

In this lesson, you will learn to create a CSS mixin using styled-components. We will create a drop shadow mixin and use it on two styled-components.

Instructor: [00:00] In this example, we're going to be working with a simple React app which uses two style components, a card, which you'll see here to the right in yellow, and a button, which you'll see here in black.

[00:15] Both of these style components are defined inside our styles.js file. You'll see we have our card and our button. To create our mixin, the first thing we're going to do is create a mixins.js file. Let's create a named export called shadow, which will be a simple arrow function that returns our CSS inside of backticks.

[00:44] Notice how all we're doing is placing the CSS that we'd like to use in our mixin -- in this case, a box shadow -- inside of backticks. to use our mixin, let's head back over to our styles.js file, import it at the top, like so, from our mixins file.

[01:09] Then to use it, let's inject it in our tagged template literal, which is our style component. Now, you'll notice the card has a slight drop shadow to it. We can also use it on the button component by injecting it there as well. Now, both of our style components are using our mixin shadow.