TypeStyle’s style function allows you to give multiple objects as an argument. This provides a simple extensible reuse-ability model. We cover typestyle mixin and mixin creators in this lesson. We also demonstrate that you have the full power of JavaScript at your disposal when using TypeStyle.
[00:00] Here, we have a simple React application that renders a div with the particular content to the document. We are going to bring in the style function from TypeStyle, and then we are going to use the style function to generate a CSS class that sets the color to red.
[00:16] We'll go ahead and assign the CSS class to the root div that is rendered by ReactDOM. The style function allows you to pass in as many style objects as you want and internally merges them all together before generating the CSS class. For example, we can pass in another style object that changes the font size to be 30 pixels.
[00:37] Supporting multiple objects within the style function allows you to easily move reusable styles out of the style function into their own variables. For example, we can move the font-size object into its own variable, and then reuse it whenever we want the same font size. At this point, font-size is essentially a mixin.
[00:57] You can even make utility functions out of such things in your code. As an example, we can convert the font-size variable into a function that takes a value of type number, and returns an object with the font-size property as desired. We finally call this function with the desired value for a particular class.
[01:18] We now have a reusable font-size mixin creator. Since such mixin creators are real JavaScript functions, you can make them as powerful as you want. For example, let's add support for string or numbers as the value argument for the font-size mixin creator.
[01:36] If the value passed in is a string, we assume it already has the correct unit and use it as it is. Otherwise, for numbers, we assume that the intended unit is pixels and add that when converting it to a string. Finally, we return our mixin, which contains the font-size CSS property.
[01:57] Now, we can use a font-size mixin creator with a number which is automatically converted to pixels, or we can pass in a string with an explicit unit. Using such mixin and mixin creators, like the font-size function, allows you to use your JavaScript code maintainability practices to manage your CSS.