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::{
  2. classes, html, Children, Classes, Component,
  3. Context, Html, Properties
  4. };
  5. #[derive(PartialEq, Properties)]
  6. struct Props {
  7. #[prop_or_default]
  8. class: Classes,
  9. fill: bool,
  10. children: Children,
  11. }
  12. struct MyComponent;
  13. impl Component for MyComponent {
  14. type Message = ();
  15. type Properties = Props;
  16. fn create(_ctx: &Context<Self>) -> Self {
  17. Self
  18. }
  19. fn view(&self, ctx: &Context<Self>) -> Html {
  20. let Props {
  21. class,
  22. fill,
  23. children,
  24. } = &ctx.props();
  25. html! {
  26. <div
  27. class={classes!(
  28. "my-container-class",
  29. fill.then(|| Some("my-fill-class")),
  30. class.clone(),
  31. )}
  32. >
  33. { children.clone() }
  34. </div>
  35. }
  36. }
  37. }