Classes

Classes

The struct Classes can be used to deal with HTML classes.

When pushing a string to the set, Classes ensures that there is one element for every class even if a single string might contain multiple classes.

Classes can also be merged by using Extend (i.e. classes1.extend(classes2)) or push() (i.e. classes1.push(classes2)). In fact, anything that implements Into<Classes> can be used to push new classes to the set.

The macro classes! is a convenient macro that creates one single Classes. Its input accepts a comma separated list of expressions. The only requirement is that every expression implements Into<Classes>.

  • Literal
  • Multiple
  • String
  • Optional
  • Vector
  • Array
  1. use yew::{classes, html};
  2. html! {
  3. <div class={classes!("container")}></div>
  4. };
  1. use yew::{classes, html};
  2. html! {
  3. <div class={classes!("class-1", "class-2")}></div>
  4. };
  1. use yew::{classes, html};
  2. let my_classes = String::from("class-1 class-2");
  3. html! {
  4. <div class={classes!(my_classes)}></div>
  5. };
  1. use yew::{classes, html};
  2. html! {
  3. <div class={classes!(Some("class"))} />
  4. };
  1. use yew::{classes, html};
  2. html! {
  3. <div class={classes!(vec!["class-1", "class-2"])}></div>
  4. };
  1. use yew::{classes, html};
  2. let my_classes = ["class-1", "class-2"];
  3. html! {
  4. <div class={classes!(my_classes.as_ref())}></div>
  5. };

Components that accept classes

  1. use yew::prelude::*;
  2. #[derive(PartialEq, Properties)]
  3. struct Props {
  4. #[prop_or_default]
  5. class: Classes,
  6. fill: bool,
  7. children: Children,
  8. }
  9. #[function_component]
  10. fn MyComponent(props: &Props) -> Html {
  11. let Props {
  12. class,
  13. fill,
  14. children,
  15. } = props;
  16. html! {
  17. <div
  18. class={classes!(
  19. "my-container-class",
  20. fill.then(|| Some("my-fill-class")),
  21. class.clone(),
  22. )}
  23. >
  24. { children.clone() }
  25. </div>
  26. }
  27. }