Type-safe Styling for React Component Packages: Vanilla Extract CSS

Unlock the power of type-safe styling in React component packages with Vanilla Extract CSS. Learn how to effortlessly write scalable and maintainable styles, leveraging CSS-in-Typescript. Discover the seamless integration of Vanilla Extract CSS and take your React components to the next level.

Rate this content
Bookmark
SlidesGithubProject website
Watch video on a separate page
Video Summary and Transcription
The video discusses Vanilla Extract CSS, a method for styling React applications with benefits like scoped styling and zero runtime overhead. It compares various styling tools, highlighting how Vanilla Extract CSS offers type-safe theming and improved performance by generating static CSS files at build time. The video explains how Vanilla Extract CSS is framework agnostic, allowing usage across different libraries like React and Vue. It also introduces tools like Sprinkles for utility classes and the recipe function for handling button variants and themes. The speaker demonstrates a simple React application using Vanilla Extract CSS with Vite, illustrating the integration of themes and design variations in component packages. The discussion covers the advantages of Vanilla Extract CSS over CSS Modules and its toolkit, including CSS utils and deeply nested tokens.

This talk has been presented at React Advanced 2023, check out the latest edition of this React Conference.

FAQ

Vanilla Extract CSS is a method for styling React applications that combines the benefits of scoped styling and zero runtime overhead. It allows for type-safe theming and provides a powerful toolkit for integrating styles seamlessly across different frameworks.

Vanilla Extract CSS improves performance by generating static CSS files at build time, eliminating any runtime overhead. This approach results in better performance, especially for large-scale applications.

Unlike CSS Modules, Vanilla Extract CSS offers a great developer experience similar to CSS-in-JS solutions, including type safety and the ability to define themes with deeply nested tokens. It combines scoped styling with zero runtime overhead.

Yes, Vanilla Extract CSS is framework agnostic, meaning it can be utilized across different libraries and frameworks, including React, Vue, and more. This makes it an ideal choice for projects that may require flexibility in terms of framework usage.

To start with Vanilla Extract CSS, you'll need to install the vanilla extract package and a bundler plugin compatible with your development environment. For instance, if using Vite as a bundler, you would install a Vite bundler plugin to handle CSS file bundling during build time.

Vanilla Extract CSS uses a function called 'create theme' to define themes with tokens that can include colors and styles. Variations can be managed using the 'recipe' function, which allows for defining different styles based on props like type, size, or state.

1. Introduction to Type-Safe Styling in React#

Short description:

Today we're going to talk about the type-safe styling method in React applications. I'm going to start with a quick comparison between some of the most popular tools for styling in React, like CSS in JS in general, CSS modules, and this new kit on the blog, Vanilla Extracts CSS. But it all comes with some costs. It has some runtime overload, and if your application is very large, you're going to end up with a large JS bundle file. Now we have CSS modules. It also offers scoped styling. It compiles down to plain CSS, which means no runtime overhead and a smaller JS bundle size. And now, enters vanilla extract CSS. Think of it as a package that marries the best of both worlds, a scoped styling, zero runtime overhead, and providing great developer experience with a CSS and TS, a beautiful syntax. So for a design system component package which needs efficiency, scalability, and maintainability, we want both performance and good developer experience. And in my opinion, vanilla extract CSS is an option worth considering. Vanilla extract generates a static CSS file at build time, so it has no runtime overhead, and as a result, it has better performance. It is framework agnostic. So you develop your styles once, and then you can use it across different libraries, whether it's React, Vue, or whatever new library your team suddenly decided to use. It has a very powerful toolkit. You're thinking about Tailwinds because of its utility classes. Well, Vanilla Extract's CSS has Sprinkles, and you might think of, Oh, but I need to do some calculation in my CSS. But Vanilla Extract offers CSS utils and some other tools that I'm going to talk about during the demo. It's also, on top of all of these features, has type safety. And with type safety, you can define themes with deeply nested tokens and let the TypeScript to take care of all of that.

Have you ever found yourself wrestling with CSS in a React application and thinking, there's got to be a better way? Sounds familiar, right? Today we're going to talk about the type-safe styling method in React applications.

Hi, my name is Negar Jamwani-Farad. I'm a software developer at Lightspeed Commerce, and my friends and colleagues know me for my passion for CSS and working on design systems. And today, I'm going to talk about one of the things that recently caught my attention. I'm going to start with a quick comparison between some of the most popular tools for styling in React, like CSS in JS in general, CSS modules, and this new kit on the blog, Vanilla Extracts CSS. And trust me, by the end of this, you're going to have a new favorite.

You might wonder, we already have so many great options. I mean, who doesn't like CSS in JS? Well, it is popular indeed. It offers scoped styling right inside the component, and it also has good developer experience with no context switching when you're going back and forth between your CSS and styling files, between your JS and styling files. But it all comes with some costs. It has some runtime overload, and if your application is very large, you're going to end up with a large JS bundle file.

Now we have CSS modules. It also offers scoped styling. It compiles down to plain CSS, which means no runtime overhead and a smaller JS bundle size. But to be fair, the developer experience is not as good as CSS and JS solutions, especially when TypeScript is in the game. And now, enters vanilla extract CSS. Think of it as a package that marries the best of both worlds, a scoped styling, zero runtime overhead, and providing great developer experience with a CSS and TS, a beautiful syntax. So for a design system component package which needs efficiency, scalability, and maintainability, we want both performance and good developer experience. And in my opinion, vanilla extract CSS is an option worth considering.

So let's dive into why vanilla extract is turning so many heads around. So I mentioned zero runtime. Vanilla extract generates a static CSS file at build time, so it has no runtime overhead, and as a result, it has better performance. It is framework agnostic. So you develop your styles once, and then you can use it across different libraries, whether it's React, Vue, or whatever new library your team suddenly decided to use. It has a very powerful toolkit. You're thinking about Tailwinds because of its utility classes. Well, Vanilla Extract's CSS has Sprinkles, and you might think of, Oh, but I need to do some calculation in my CSS. But Vanilla Extract offers CSS utils and some other tools that I'm going to talk about during the demo. It's also, on top of all of these features, has type safety. And with type safety, you can define themes with deeply nested tokens and let the TypeScript to take care of all of that.

2. Using Vanilla Extract CSS with React#

Short description:

Let's jump into code and see it in practice. I have a very simple React application created with Vite. We're going to mimic creating components in design system component packages. To start, we need to add vanilla extract CSS. We also need to install a Vit Bundler plugin to bundle our CSS files. Then, we create a basic setting for the button and export the styling. Finally, we export the button style in our button component.

Or auto-complete, and not missing out token change somewhere in your application. So I think I talked a lot about Vanilla Extract so far. Let's jump into code and see it in practice, and see what it is all about.

So let me switch to my editor, here. So here I have a very simple React application. I've created this with Vite. It's TypeScript, React, and Vite as a bundler. I've created a very, very simple button component, here. We're going to mimic creating components in design system component packages, and I'm going to try my best that in a very short time, create themes, add variation to this button, and I'll add all the styling to this button. So right now if you want to check out the component, it looks like this. It's basically the basic HTML button.

So we have to start with adding vanilla extract CSS. To start that, there are two packages that we need to install. And one of them is vanilla extract itself, and the other one is recipe. I'm going to talk about recipe later in this talk. But I have them right now installed just for the sake of time, so we don't have to install them.

So another package that you need to start at the beginning of a project is a bundler. And vanilla extract CSS offers a couple of bundler integrations with different platforms. Right now, I'm using Vit, so I need to install a Vit Bundler plugin to be able to bundle our CSS files at the build time. So to configure that, we need to head over to vit.config and, as you can see, I've already done it, you import the plugin and then add it to your Vit config. And as simple as that, you're all set. You have everything set up to start writing your stuff. So the first thing I'm going to create is a very basic setting for my button so it's not just the boring HTML button. So in my component folder, I'm going to add a button.css.ts file, and that's why we need the bundler. And I'm going to create, I'm going to call it button style, oh my god, I hate live coding. So there is a style function in vanilla CSS that we're going to use here. And for the sake of time, I'm just going to copy and paste from my notes the styling that I have created for this component. So very basic styling, like hover and focus and everything. And we need to export this from this file. And then, now we head back to our button, and here for the class name, I'm going to export the button style that I exported in my other file.

3. Adding Themes to Button Styling#

Short description:

Now let's add colors and borders to the button using values from a theme. We create a theme using the create theme function, which creates CSS variables for the theme tokens. We can then use these values in our styling. We can also add multiple themes by creating additional classes and variables. Finally, our application is wrapped in a component called themeSweepter, which allows us to switch between themes.

Very similar to what we do in CSS modules. So now let's have a look at it in the browser, and as you can see, this file has been applied, and as simple as that.

Okay, now I want to add some colors and some borders to my button, but I don't want to just hard code these values into my CSS. I want to use the values coming from a theme. So we need to create a theme. So I have created a theme.css.ts file. And in this file, I'm going to create a default theme, and I'm going to use another function from vanilla Extract CSS, which is called create theme, very intuitive. And in this file, I'm going to pass in the tokens I want to have for my theme. So I have a very simplified token structure here ready for the sake of demo. It only has like two colors, but it can be the whole theme that you want for your application. What create theme here does for us is that it creates CSS variables for every single of these tokens, and then wraps these values with a class. And this class is exposed here as, I'm going to call it default theme class. And then as second parameter, it also returns a var. I like to call it a var. And this is actually a data structure following the exact structure that we provided in our token here. And then we can use it in our styling to get these values in my, for example, button.css.ts5.

So now we have so far one theme for our application. But let's just go beyond that and add another color. So let's say I want to have another pink theme. And I'm going to use the same create theme function, but this time as first parameter I'm going to pass in vars because I don't want to, I want to follow the same pattern. So this is the way, this is how we tell, when you're going to extract CSS, that I'm going to follow the same structure. And as second parameter, I'm going to pass in my new values that's going to overwrite the previous one. So here, I'm going to pass in my pink theme values. So I need to export all of these values at the end. So I have a default class, I have a pink theme class, and then I have my vars. And then I have created, my whole application is wrapped by a component called themeSweepter. It's just a simple component that switches the class on top level from one theme to another so that we can... Let's see, probably I had some typo... Okay. And okay, let's head back to our component.

4. Using Theme Values and Variants in Button Styling#

Short description:

In this part, we learn how to use the values of the theme in our button styling. We also explore how to implement different variants of the button based on props using the recipe function. The recipe function allows us to define different types of buttons and override the base styling. We can easily specify the default variant and generate the necessary class names. With Vanilla Extract, we can create a button with multiple variations and themes effortlessly.

So as you can see, this part has added but it's not working because we're not using the values of the theme. So I go back to my button.css.ts and for the background color, I'm going to import the vars that I exported there in my theme and here I'm going to say pick the colors primary and main. And I'm going to use another one here. So I want the color black. Look at that. Autocomplete. Oh my god. It's so exciting. So and then I'm going to use the dark theme for my hover and for my outline, I'm going to use another color. So I'm just going to go with grey and main. Now let's go back to our computer. Go to our browser and as you can see the theme has been applied and now let's switch theme. We have our two colors in two themes within a few minutes.

So in the component packages, it normally happens that we want to pass in a prop to our component like a variant, a type, a size, and then based on the prop that we pass to the component we want to be able to change our design and our styling of the component. So for that we need to use recipe. So to start implementing that I'm going to replace the style with the recipe function and I need to move all of these stylings under base. So it's going to be the basis styling of my component. So I'm going to comment out these because we are going to move them in another section and recipe provides a variant, oh sorry, I guess variance, yes. So variance can be anything from type to size, even it can be a boolean like disabled. So here I'm just going to create a type variant and I want my type variant to have a fill and then I want it to have outline. So these are going to be different types of my bun and I want a simple text type without any background or anything. So now we need to add all the styling for each and every of these types that is supposed to overwrite the base styling that we have up here. So I have it ready so I'm going to copy and paste it from my notes. So if I can, apparently, I use my ability to copy and paste. And the text. So here we go. It's just simply adding background and hover for each type. But there is one more thing that we need to do. We need to tell Banyuda Extract which one is our default variant. So we say, for default variants, for type, I want it to be fill. And since it's TypeScript, it's fully typed, so it has great suggestions. If we want to implement that into a button, normally what you should do is to add the type here, and then you need to add it to your props type, but then you have to follow the exact naming from your styling, and keeping these in sync over time is a hustle. So you got to go, type, I want it to be fill, and then blah, blah, and keeping that consistent over time is really hard, but you don't really have to do that with Vanilla Xtract, there is a tool, so I'm going to say, I'm going to export button variant, and I'm going to use recipe, recipe, help me, oh my god, oh, sorry, my bad, I need to, okay, there you go, and I'm going to say get all the types from button style, and button style is not a class anymore, so it's whatever is returned from recipe. So now go back to our component and I will import the type that I have just created, what's called bun variants, there you go, and then I'm going to add my new prop, and here we're going to say for my class name, now the bun side as I mentioned is not a simple string anymore, it's a function and you pass in your type prop here, and based on the prop that you're passing it will return the correct class that you need for your component. So there's one last thing that I need to do, is to add these props here, so I want to have outline, and then I want to have text, and the first one it has a default value which is fill. Now let's go back to our browser, and ta-da, we have three variants of the same button, Let's see if the theme works, and yes it does, and as easy as that, within a few minutes I have been able to create a button with three variations and two themes, and that's the power of vanilla extract.

Negar Jamalifard
Negar Jamalifard
19 min
23 Oct, 2023

Comments

Sign in or register to post your comment.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Design Systems: Walking the Line Between Flexibility and Consistency
React Advanced 2021React Advanced 2021
47 min
Design Systems: Walking the Line Between Flexibility and Consistency
Top Content
The Talk discusses the balance between flexibility and consistency in design systems. It explores the API design of the ActionList component and the customization options it offers. The use of component-based APIs and composability is emphasized for flexibility and customization. The Talk also touches on the ActionMenu component and the concept of building for people. The Q&A session covers topics such as component inclusion in design systems, API complexity, and the decision between creating a custom design system or using a component library.
React's Most Useful Types
React Day Berlin 2023React Day Berlin 2023
21 min
React's Most Useful Types
Top Content
Watch video: React's Most Useful Types
Today's Talk focuses on React's best types and JSX. It covers the types of JSX and React components, including React.fc and React.reactnode. The discussion also explores JSX intrinsic elements and react.component props, highlighting their differences and use cases. The Talk concludes with insights on using React.componentType and passing components, as well as utilizing the react.element ref type for external libraries like React-Select.
TypeScript and React: Secrets of a Happy Marriage
React Advanced 2022React Advanced 2022
21 min
TypeScript and React: Secrets of a Happy Marriage
Top Content
React and TypeScript have a strong relationship, with TypeScript offering benefits like better type checking and contract enforcement. Failing early and failing hard is important in software development to catch errors and debug effectively. TypeScript provides early detection of errors and ensures data accuracy in components and hooks. It offers superior type safety but can become complex as the codebase grows. Using union types in props can resolve errors and address dependencies. Dynamic communication and type contracts can be achieved through generics. Understanding React's built-in types and hooks like useState and useRef is crucial for leveraging their functionality.
Making Magic: Building a TypeScript-First Framework
TypeScript Congress 2023TypeScript Congress 2023
31 min
Making Magic: Building a TypeScript-First Framework
Top Content
Daniel Rowe discusses building a TypeScript-first framework at TypeScript Congress and shares his involvement in various projects. Nuxt is a progressive framework built on Vue.js, aiming to reduce friction and distraction for developers. It leverages TypeScript for inference and aims to be the source of truth for projects. Nuxt provides type safety and extensibility through integration with TypeScript. Migrating to TypeScript offers long-term maintenance benefits and can uncover hidden bugs. Nuxt focuses on improving existing tools and finds inspiration in frameworks like TRPC.
Stop Writing Your Routes
Vue.js London 2023Vue.js London 2023
30 min
Stop Writing Your Routes
Designing APIs is a challenge, and it's important to consider the language used and different versions of the API. API ergonomics focus on ease of use and trade-offs. Routing is a misunderstood aspect of API design, and file-based routing can simplify it. Unplugging View Router provides typed routes and eliminates the need to pass routes when creating the router. Data loading and handling can be improved with data loaders and predictable routes. Handling protected routes and index and ID files are also discussed.
Faster TypeScript builds with --isolatedDeclarations
TypeScript Congress 2023TypeScript Congress 2023
24 min
Faster TypeScript builds with --isolatedDeclarations
Top Content
This talk discusses the performance issues in TypeScript builds and introduces a new feature called isolated declarations. By running the compiler in parallel and using isolated modules, significant performance gains can be achieved. Isolated declarations improve build speed, compatibility with other tools, and require developers to write types in code. This feature has the potential to further increase performance and may be available in TypeScript soon.

Workshops on related topic

React, TypeScript, and TDD
React Advanced 2021React Advanced 2021
174 min
React, TypeScript, and TDD
Top Content
Featured WorkshopFree
Paul Everitt
Paul Everitt
ReactJS is wildly popular and thus wildly supported. TypeScript is increasingly popular, and thus increasingly supported.

The two together? Not as much. Given that they both change quickly, it's hard to find accurate learning materials.

React+TypeScript, with JetBrains IDEs? That three-part combination is the topic of this series. We'll show a little about a lot. Meaning, the key steps to getting productive, in the IDE, for React projects using TypeScript. Along the way we'll show test-driven development and emphasize tips-and-tricks in the IDE.
Mastering advanced concepts in TypeScript
React Summit US 2023React Summit US 2023
132 min
Mastering advanced concepts in TypeScript
Top Content
Featured WorkshopFree
Jiri Lojda
Jiri Lojda
TypeScript is not just types and interfaces. Join this workshop to master more advanced features of TypeScript that will make your code bullet-proof. We will cover conditional types and infer notation, template strings and how to map over union types and object/array properties. Each topic will be demonstrated on a sample application that was written with basic types or no types at all and we will together improve the code so you get more familiar with each feature and can bring this new knowledge directly into your projects.
You will learn:- - What are conditional types and infer notation- What are template strings- How to map over union types and object/array properties.
Deep TypeScript Tips & Tricks
Node Congress 2024Node Congress 2024
83 min
Deep TypeScript Tips & Tricks
Top Content
Featured Workshop
Josh Goldberg
Josh Goldberg
TypeScript has a powerful type system with all sorts of fancy features for representing wild and wacky JavaScript states. But the syntax to do so isn't always straightforward, and the error messages aren't always precise in telling you what's wrong. Let's dive into how many of TypeScript's more powerful features really work, what kinds of real-world problems they solve, and how to wrestle the type system into submission so you can write truly excellent TypeScript code.
Best Practices and Advanced TypeScript Tips for React Developers
React Advanced 2022React Advanced 2022
148 min
Best Practices and Advanced TypeScript Tips for React Developers
Top Content
Featured Workshop
Maurice de Beijer
Maurice de Beijer
Are you a React developer trying to get the most benefits from TypeScript? Then this is the workshop for you.In this interactive workshop, we will start at the basics and examine the pros and cons of different ways you can declare React components using TypeScript. After that we will move to more advanced concepts where we will go beyond the strict setting of TypeScript. You will learn when to use types like any, unknown and never. We will explore the use of type predicates, guards and exhaustive checking. You will learn about the built-in mapped types as well as how to create your own new type map utilities. And we will start programming in the TypeScript type system using conditional types and type inferring.
Building Your Own Custom Type System
React Summit 2024React Summit 2024
38 min
Building Your Own Custom Type System
Featured Workshop
Kunal Dubey
Kunal Dubey
I'll introduce the audience to a concept where they can have end-to-end type systems that helps ensure typesafety across the teams Such a system not only improves communication between teams but also helps teams collaborate effectively and ship way faster than they used to before. By having a custom type system, teams can also identify the errors and modify the API contracts on their IDE, which contributes to a better Developer Experience. The workshop would primarily leverage TS to showcase the concept and use tools like OpenAPI to generate the typesystem on the client side. 
Frictionless Development With Unified Type System
JSNation 2024JSNation 2024
113 min
Frictionless Development With Unified Type System
Featured Workshop
Ejiro Asiuwhu
Ejiro Asiuwhu
Imagine developing where frontend and backend sing in harmony, types dance in perfect sync, and errors become a distant memory. That's the magic of TypeScript Nirvana!
Join me on a journey to unveil the secrets of unified type definitions, the key to unlocking frictionless development. We'll dive into:
- Shared language, shared love: Define types once, share them everywhere. Consistency becomes your BFF, errors your worst nightmare (one you'll rarely see).- Effortless coding: Ditch the manual grind of type checking. TypeScript's got your back, freeing you to focus on building awesomeness.- Maintainability magic: With crystal-clear types guiding your code, maintaining it becomes a walk in the park. More time innovating, less time debugging.- Security fortress: TypeScript's type system shields your app from common vulnerabilities, making it a fortress against security threats.