#dom #class-name #macro #web

classes

Dependency-free macro that simplifies the process of building class strings for DOM elements

1 stable release

1.0.0 Apr 15, 2023

#1408 in Rust patterns

Download history 6/week @ 2024-07-29 270/week @ 2024-08-05 7/week @ 2024-08-12 40/week @ 2024-08-26 181/week @ 2024-09-02 64/week @ 2024-09-09 13/week @ 2024-09-23 10/week @ 2024-09-30 19/week @ 2024-10-07 32/week @ 2024-10-14 4/week @ 2024-10-21 10/week @ 2024-10-28 16/week @ 2024-11-04

63 downloads per month
Used in unocss-classes

MIT/Apache

6KB
95 lines

classes

classes is a lightweight and dependency-free macro that simplifies the process of building class strings for DOM elements. It accepts a variable number of arguments and combines them into a single class string. This macro is designed after the popular classnames npm package, which is commonly used in React and other frameworks.

Usage

You can supply string types or types that can be transformed into a string to the macro:

  • Option<String> / Option<&str> will use the inner value if the option is Some, and ignore the option if it's None
  • String / &str will be applied as is
  • The special syntax string_expr => bool_expr will use the string_expr when bool_expr evaluates to true

Using the Classes macro can simplify your code by reducing the boilerplate needed to build class strings.

Example

use classes::classes;

fn main() {
    let optional = Some("lumos");
    let is_night = true;

    let class = classes!["hogwarts", optional, "hogwarts--at-night" => is_night, "wingardium-leviosa" => false];

    println!("{class}"); // => 'hogwarts lumos hogwarts--at-night'
}

Dioxus Example

use classes::classes;

pub fn Button<'a>(cx: Scope<'a, ButtonProps<'a>>) -> Element {
    let class = classes!["button", "button--disabled" => cx.props.disabled, cx.props.class];

    cx.render(rsx! {
      button { class }
    })
}

No runtime deps