CVA in React
Class Variance Authority (CVA) is a utility for managing CSS class names based on various conditions. It helps create consistent and maintainable styles in
Reactcomponents by defining variants and conditional classes in a structured manner.
Why Use CVA?
- Consistency: Ensures consistent styling across your application.
- Maintainability: Simplifies managing conditional class names.
- Readability: Improves the readability of your components’ styling logic.
In React you can implement a CVA component via the
class-variance-authoritylibrary:
<Button>using CVA:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33import React from 'react'; import { cva } from 'class-variance-authority'; const buttonStyles = cva( 'base-button', { variants: { size: { small: 'button-small', medium: 'button-medium', large: 'button-large', }, color: { primary: 'button-primary', secondary: 'button-secondary', }, }, defaultVariants: { size: 'medium', color: 'primary', }, } ); const Button = ({ size, color, children }) => { return ( <button className={buttonStyles({ size, color })}> {children} </button> ); }; export default Button;Usage of the
<Button>component:
1 2 3 4 5 6 7 8 9 10 11 12 13 14import React from 'react'; import Button from './Button'; const App = () => { return ( <div> <Button size="small" color="primary">Small Primary Button</Button> <Button size="medium" color="secondary">Medium Secondary Button</Button> <Button size="large" color="primary">Large Primary Button</Button> </div> ); }; export default App;
(Referenced from: Media - Lorem ipsum)
CVA in Drupal
To make the html_cva twig function available in a Drupal environment, you can install this contributed module: CVA (Class Variance Authority) (link), below is an example usage of this function to create an Alert component.
Below are the code for the Alert SDC component:
your_theme_name/components/alert.component.yml
| |
your_theme_name/components/alert.twig
| |
And here’s an example usage using {{ include() }}

Reference & Useful Link
- Drupal Contributed Module - CVA (Class Variant Authority): link
- Twig Documentation - Function
html_cva(): link - Medium - Introduction to Class Variance Authority (CVA) in React - Lorem ipsum: link
- GitHub -
twigphp / html-extra: link (composer: link) - GitHub -
twigphp /twig-extra-bundle: link (composer: link)