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

Rate this content
Bookmark
SlidesGithubProject website

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.

Negar Jamalifard
Negar Jamalifard
19 min
23 Oct, 2023

Comments

Sign in or register to post your comment.

Video Summary and Transcription

Today's Talk introduces Vanilla Extract CSS, a type-safe styling method for React applications. It combines the benefits of scoped styling, zero runtime overhead, and a great developer experience. Vanilla Extract generates a static CSS file at build time, resulting in better performance. It is framework agnostic and offers a powerful toolkit, including Sprinkles for utility classes and CSS utils for calculations. With type safety and the ability to define themes and variants, Vanilla Extract makes it easy to create efficient, scalable, and maintainable design system component packages.

Available in Español

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.

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 Conference 2021React Advanced Conference 2021
47 min
Design Systems: Walking the Line Between Flexibility and Consistency
Top Content
Design systems aim to bring consistency to a brand's design and make the UI development productive. Component libraries with well-thought API can make this a breeze. But, sometimes an API choice can accidentally overstep and slow the team down! There's a balance there... somewhere. Let's explore some of the problems and possible creative solutions.
TypeScript and React: Secrets of a Happy Marriage
React Advanced Conference 2022React Advanced Conference 2022
21 min
TypeScript and React: Secrets of a Happy Marriage
Top Content
TypeScript and React are inseparable. What's the secret to their successful union? Quite a lot of surprisingly strange code. Learn why useRef always feels weird, how to wrangle generics in custom hooks, and how union types can transform your components.
React's Most Useful Types
React Day Berlin 2023React Day Berlin 2023
21 min
React's Most Useful Types
Top Content
We don't think of React as shipping its own types. But React's types are a core part of the framework - overseen by the React team, and co-ordinated with React's major releases.In this live coding talk, we'll look at all the types you've been missing out on. How do you get the props type from a component? How do you know what ref a component takes? Should you use React.FC? And what's the deal with JSX.Element?You'll walk away with a bunch of exciting ideas to take to your React applications, and hopefully a new appreciation for the wonders of React and TypeScript working together.
Stop Writing Your Routes
Vue.js London 2023Vue.js London 2023
30 min
Stop Writing Your Routes
The more you keep working on an application, the more complicated its routing becomes, and the easier it is to make a mistake. ""Was the route named users or was it user?"", ""Did it have an id param or was it userId?"". If only TypeScript could tell you what are the possible names and params. If only you didn't have to write a single route anymore and let a plugin do it for you. In this talk we will go through what it took to bring automatically typed routes for Vue Router.
Making Magic: Building a TypeScript-First Framework
TypeScript Congress 2023TypeScript Congress 2023
31 min
Making Magic: Building a TypeScript-First Framework
I'll dive into the internals of Nuxt to describe how we've built a TypeScript-first framework that is deeply integrated with the user's IDE and type checking setup to offer end-to-end full-stack type safety, hints for layouts, middleware and more, typed runtime configuration options and even typed routing. Plus, I'll highlight what I'm most excited about doing in the days to come and how TypeScript makes that possible not just for us but for any library author.
Full-stack & typesafe React (+Native) apps with tRPC.io
React Advanced Conference 2021React Advanced Conference 2021
6 min
Full-stack & typesafe React (+Native) apps with tRPC.io
Top Content
Why are we devs so obsessed with decoupling things that are coupled nature? tRPC is a library that replaces the need for GraphQL or REST for internal APIs. When using it, you simply write backend functions whose input and output shapes are instantly inferred in your frontend without any code generation; making writing API schemas a thing of the past. It's lightweight, not tied to React, HTTP-cacheable, and can be incrementally adopted. In this talk, I'll give a glimpse of the DX you can get from tRPC and how (and why) to get started.

Workshops on related topic

React, TypeScript, and TDD
React Advanced Conference 2021React Advanced Conference 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.
Best Practices and Advanced TypeScript Tips for React Developers
React Advanced Conference 2022React Advanced Conference 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.
Deep TypeScript Tips & Tricks
Node Congress 2024Node Congress 2024
83 min
Deep TypeScript Tips & Tricks
Top Content
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.
Practice TypeScript Techniques Building React Server Components App
TypeScript Congress 2023TypeScript Congress 2023
131 min
Practice TypeScript Techniques Building React Server Components App
Workshop
Maurice de Beijer
Maurice de Beijer
In this hands-on workshop, Maurice will personally guide you through a series of exercises designed to empower you with a deep understanding of React Server Components and the power of TypeScript. Discover how to optimize your applications, improve performance, and unlock new possibilities.
 
During the workshop, you will:
- Maximize code maintainability and scalability with advanced TypeScript practices
- Unleash the performance benefits of React Server Components, surpassing traditional approaches
- Turbocharge your TypeScript with the power of Mapped Types
- Make your TypeScript types more secure with Opaque Types
- Explore the power of Template Literal Types when using Mapped Types
 
Maurice will virtually be by your side, offering comprehensive guidance and answering your questions as you navigate each exercise. By the end of the workshop, you'll have mastered React Server Components, armed with a newfound arsenal of TypeScript knowledge to supercharge your React applications.
 
Don't miss this opportunity to elevate your React expertise to new heights. Join our workshop and unlock the potential of React Server Components with TypeScript. Your apps will thank you.
Advanced TypeScript types for fun and reliability
TypeScript Congress 2022TypeScript Congress 2022
116 min
Advanced TypeScript types for fun and reliability
Workshop
Maurice de Beijer
Maurice de Beijer
If you're looking to get the most out of TypeScript, this workshop is for you! In this interactive workshop, we will explore the use of advanced types to improve the safety and predictability of your TypeScript code. You will learn when to use types like unknown or never. We will explore the use of type predicates, guards and exhaustive checking to make your TypeScript code more reliable both at compile and run-time. 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.
Are you familiar with the basics of TypeScript and want to dive deeper? Then please join me with your laptop in this advanced and interactive workshop to learn all these topics and more.
You can find the slides, with links, here: http://theproblemsolver.nl/docs/ts-advanced-workshop.pdf
And the repository we will be using is here: https://github.com/mauricedb/ts-advanced
Mastering Node.js Test Runner
TestJS Summit 2023TestJS Summit 2023
78 min
Mastering Node.js Test Runner
Workshop
Marco Ippolito
Marco Ippolito
Node.js test runner is modern, fast, and doesn't require additional libraries, but understanding and using it well can be tricky. You will learn how to use Node.js test runner to its full potential. We'll show you how it compares to other tools, how to set it up, and how to run your tests effectively. During the workshop, we'll do exercises to help you get comfortable with filtering, using native assertions, running tests in parallel, using CLI, and more. We'll also talk about working with TypeScript, making custom reports, and code coverage.