Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
class-variance-authority
Advanced tools
The class-variance-authority (CVA) npm package is a utility for managing and composing CSS class names in a more declarative and type-safe manner. It helps in creating consistent and reusable class name patterns, especially useful in component-based frameworks like React.
Defining Variants
This feature allows you to define variants for your CSS classes. You can specify different styles for different states or conditions, making it easier to manage complex styling logic.
const button = cva('btn', {
variants: {
size: {
small: 'btn-small',
large: 'btn-large'
},
color: {
primary: 'btn-primary',
secondary: 'btn-secondary'
}
},
defaultVariants: {
size: 'small',
color: 'primary'
}
});
// Usage
const className = button({ size: 'large', color: 'secondary' });
Combining Variants
This feature allows you to combine multiple variant definitions into a single class name. It helps in creating more complex and reusable class name patterns.
const button = cva('btn', {
variants: {
size: {
small: 'btn-small',
large: 'btn-large'
},
color: {
primary: 'btn-primary',
secondary: 'btn-secondary'
}
}
});
const iconButton = cva(button, {
variants: {
icon: {
left: 'btn-icon-left',
right: 'btn-icon-right'
}
}
});
// Usage
const className = iconButton({ size: 'large', color: 'primary', icon: 'left' });
Type Safety
CVA provides type safety when defining and using variants. This ensures that you are using the correct variant names and values, reducing the likelihood of runtime errors.
const button = cva('btn', {
variants: {
size: {
small: 'btn-small',
large: 'btn-large'
},
color: {
primary: 'btn-primary',
secondary: 'btn-secondary'
}
}
});
// TypeScript will enforce correct usage
const className: string = button({ size: 'large', color: 'primary' });
The classnames package is a simple utility for conditionally joining class names together. It is less feature-rich compared to CVA but is widely used for its simplicity and ease of use. Unlike CVA, it does not provide built-in support for defining and managing variants.
Styled-components is a library for styling React components using tagged template literals. It offers a more comprehensive solution for styling, including support for themes and dynamic styling. However, it is more complex and has a steeper learning curve compared to CVA.
Emotion is a library designed for writing CSS styles with JavaScript. It provides powerful and flexible styling capabilities, including support for CSS-in-JS, theming, and more. While it offers more features than CVA, it is also more complex and may be overkill for simpler use cases.
Class Variance Authority
CSS-in-TS libraries such as Stitches and Vanilla Extract are fantastic options for building type-safe UI components; taking away all the worries of class names and StyleSheet composition.
…but CSS-in-TS (or CSS-in-JS) isn't for everyone.
You may need full control over your StyleSheet output. Your job might require you to use a framework such as Tailwind CSS. You might just prefer writing your own CSS.
Creating variants with the "traditional" CSS approach can become an arduous task; manually matching classes to props and manually adding types.
CVA aims to take those pain points away, allowing you to focus on the more fun aspects of UI development.
variants
API movement – your open-source contributions are immensely appreciatedclb
library, but after some discussion with Bill, we felt it was best to go down the route of a separate project.npm i class-variance-authority
Unfortunately, yes. Originally, the plan was the publish the package as cva
, but this name has been taken and marked as a "placeholder". I've reached out to the author and NPM support, but have yet to hear back.
In the meantime, you can always alias the package for your convenience…
Add the alias to your tsconfig.json
paths
:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"cva": ["node_modules/class-variance-authority"]
}
}
}
Then import like so:
import { cva } from "cva";
// …
Disclaimer: Although
cva
is a tiny library, it's best to use in a SSR/SSG environment – your user probably doesn't need this JavaScript, especially for static components.
To kick things off, let's build a "basic" button
component, using cva
to handle our variant's classes
Note: Use of Tailwind CSS is optional
import { cva } from "class-variance-authority";
const button = cva(["font-semibold", "border", "rounded"], {
variants: {
intent: {
primary: [
"bg-blue-500",
"text-white",
"border-transparent",
"hover:bg-blue-600",
],
// **or**
// primary: "bg-blue-500 text-white border-transparent hover:bg-blue-600",
secondary: [
"bg-white",
"text-gray-800",
"border-gray-400",
"hover:bg-gray-100",
],
},
size: {
small: ["text-sm", "py-1", "px-2"],
medium: ["text-base", "py-2", "px-4"],
},
},
compoundVariants: [{ intent: "primary", size: "medium", class: "uppercase" }],
defaultVariants: {
intent: "primary",
size: "medium",
},
});
button();
// => "font-semibold border rounded bg-blue-500 text-white border-transparent hover:bg-blue-600 text-base py-2 px-4 uppercase"
button({ intent: "secondary", size: "small" });
// => "font-semibold border rounded bg-white text-gray-800 border-gray-400 hover:bg-gray-100 text-sm py-1 px-2"
cva
offers the VariantProps
helper to extract variant types
// styles/components.ts
import type * as CVA from "class-variance-authority";
import { cva, cx } from "class-variance-authority";
/**
* YourComponent
*/
export type YourComponentProps = CVA.VariantProps<typeof yourComponent>;
export const yourComponent = cva(/* ... */);
Whilst cva
doesn't yet offer a built-in method for composing classes, it does offer the tools to extend components on your own terms…
For example; two cva
styles, concatenated together with cx
:
// styles/components.ts
import type * as CVA from "class-variance-authority";
import { cva, cx } from "class-variance-authority";
/**
* Box
*/
export type BoxProps = CVA.VariantProps<typeof box>;
export const box = cva(["box", "box-border"], {
variants: {
margin: { 0: "m-0", 2: "m-2", 4: "m-4", 8: "m-8" },
padding: { 0: "p-0", 2: "p-2", 4: "p-4", 8: "p-8" },
},
defaultVariants: {
margin: 0,
padding: 0,
},
});
/**
* Card
*/
type CardBaseProps = CVA.VariantProps<typeof cardBase>;
const cardBase = cva(["card", "border-solid", "border-slate-300", "rounded"], {
variants: {
shadow: {
md: "drop-shadow-md",
lg: "drop-shadow-lg",
xl: "drop-shadow-xl",
},
},
});
export interface CardProps extends BoxProps, CardBaseProps {}
export const card = ({ margin, padding, shadow }: CardProps = {}) =>
cx(box({ margin, padding }), cardBase({ shadow }));
cva
Builds a class variance authority
const component = cva("base", options);
base
: the base class name (string
, string[]
or null
)options
(optional)
variants
: your variants schemacompoundVariants
: variants based on a combination of previously defined variantsdefaultVariants
: set default values for previously defined variantscx
Concatenates class names
const className = cx(classes);
classes
: array of classes to be concatenated⚠️ Warning: The examples below are purely demonstrative and haven't been tested thoroughly (yet)
/* styles.css */
.button {
/* */
}
.button--primary {
/* */
}
.button--secondary {
/* */
}
.button--small {
/* */
}
.button--medium {
/* */
}
.button--primary-small {
/* */
}
import { cva } from "class-variance-authority";
const button = cva("button", {
variants: {
intent: {
primary: "button--primary",
secondary: "button--secondary",
},
size: {
small: "button--small",
medium: "button--medium",
},
},
compoundVariants: [
{ intent: "primary", size: "medium", class: "button--primary-small" },
],
defaultVariants: {
intent: "primary",
size: "medium",
},
});
button();
// => "button button--primary button--medium"
button({ intent: "secondary", size: "small" });
// => "button button--secondary button--small"
// button.11ty.js
const { cva } = require("class-variance-authority");
// ⚠️ Disclaimer: Use of Tailwind CSS is optional
const button = cva("button", {
variants: {
intent: {
primary: [
"bg-blue-500",
"text-white",
"border-transparent",
"hover:bg-blue-600",
],
secondary: [
"bg-white",
"text-gray-800",
"border-gray-400",
"hover:bg-gray-100",
],
},
size: {
small: ["text-sm", "py-1", "px-2"],
medium: ["text-base", "py-2", "px-4"],
},
},
compoundVariants: [{ intent: "primary", size: "medium", class: "uppercase" }],
defaultVariants: {
intent: "primary",
size: "medium",
},
});
module.exports = function ({ label, intent, size }) {
return `<button class="${button({ intent, size })}">${label}</button>`;
};
/* button.css */
.base {
/* */
}
.primary {
/* */
}
.secondary {
/* */
}
.small {
/* */
}
.medium {
/* */
}
.primaryMedium {
/* */
}
// button.tsx
import React from "react";
import { cva } from "class-variance-authority";
import * as CVA from "class-variance-authority";
import {
base,
primary,
secondary,
small,
medium,
primaryMedium,
} from "./button.css";
// ⚠️ Disclaimer: Use of Tailwind CSS is optional
const button = cva(base, {
variants: {
intent: {
primary,
secondary,
},
size: {
small,
medium,
},
},
compoundVariants: [
{ intent: "primary", size: "medium", class: primaryMedium },
],
defaultVariants: {
intent: "primary",
size: "medium",
},
});
export type ButtonProps = CVA.VariantProps<typeof button>;
export const Button: React.FC<ButtonProps> = ({ intent, size, ...props }) => (
<button className={button({ intent, size })} {...props} />
);
// button.tsx
import React from "react";
import { cva } from "class-variance-authority";
import * as CVA from "class-variance-authority";
// ⚠️ Disclaimer: Use of Tailwind CSS is optional
const button = cva("button", {
variants: {
intent: {
primary: [
"bg-blue-500",
"text-white",
"border-transparent",
"hover:bg-blue-600",
],
secondary: [
"bg-white",
"text-gray-800",
"border-gray-400",
"hover:bg-gray-100",
],
},
size: {
small: ["text-sm", "py-1", "px-2"],
medium: ["text-base", "py-2", "px-4"],
},
},
compoundVariants: [{ intent: "primary", size: "medium", class: "uppercase" }],
defaultVariants: {
intent: "primary",
size: "medium",
},
});
export type ButtonProps = CVA.VariantProps<typeof button>;
export const Button: React.FC<ButtonProps> = ({ intent, size, ...props }) => (
<button className={button({ intent, size })} {...props} />
);
<!-- button.svelte -->
<script lang="ts">
import { cva } from "class-variance-authority";
import type * as CVA from "class-variance-authority";
const button = cva("button", {
variants: {
intent: {
primary: "button--primary",
secondary: "button--secondary",
},
size: {
small: "button--small",
medium: "button--medium",
},
},
compoundVariants: [
{ intent: "primary", size: "medium", class: "button--primary-medium" },
],
defaultVariants: {
intent: "primary",
size: "medium",
},
});
type ButtonProps = CVA.VariantProps<typeof button>;
export let intent: ButtonProps["intent"];
export let size: ButtonProps["size"];
</script>
<button class={button({ intent, size })}><slot /></button>
<style>
.button { /* … */ }
.button--primary { /* … */ }
.button--secondary { /* … */ }
.button--small { /* … */ }
.button--medium { /* … */ }
.button--primary-medium { /* … */ }
</style>
<!-- button.vue -->
<script lang="ts">
import { defineComponent } from "vue";
import { cva } from "class-variance-authority";
import type * as CVA from "class-variance-authority";
const button = cva("button", {
variants: {
intent: {
primary: "button--primary",
secondary: "button--secondary",
},
size: {
small: "button--small",
medium: "button--medium",
},
},
compoundVariants: [
{ intent: "primary", size: "medium", class: "button--primary-medium" },
],
defaultVariants: {
intent: "primary",
size: "medium",
},
});
type ButtonProps = CVA.VariantProps<typeof button>;
export default defineComponent({
props: ["intent" as ButtonProps["intent"], "size" as ButtonProps["size"]],
methods: {
button,
},
});
</script>
<template>
<button :class="button({ intent, size })">
<slot></slot>
</button>
</template>
<style>
.button {
/* … */
}
.button--primary {
/* … */
}
.button--secondary {
/* … */
}
.button--small {
/* … */
}
.button--medium {
/* … */
}
.button--primary-medium {
/* … */
}
</style>
Although primarily designed for handling class names, at its core, cva
is really just a fancy way of managing a string…
const greeter = cva("Good morning!", {
variants: {
isLoggedIn: {
true: "Here's a secret only logged in users can see",
false: "Log in to find out more…",
},
},
defaultVariants: {
isLoggedIn: "false",
},
});
greeter();
// => "Good morning! Log in to find out more…"
greeter({ isLoggedIn: "true" });
// => "Good morning! Here's a secret only logged in users can see"
FAQs
Class Variance Authority 🧬
The npm package class-variance-authority receives a total of 0 weekly downloads. As such, class-variance-authority popularity was classified as not popular.
We found that class-variance-authority demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.