Skip to main content

component

Attribute Macro component 

Source
#[component]
Expand description

Turn a function into a reusable component, React style.

use rok_ui::prelude::*;

/// A greeting card.
#[component]
pub fn Greeting(
    name: SharedString,
    #[default] excited: bool,
    #[default] on_wave: Option<EventHandler<ClickEvent>>,
    #[children] children: Vec<AnyElement>,
    window: &mut Window,
    cx: &mut App,
) -> impl IntoElement {
    div().child(format!("Hello, {name}{}", if excited { "!" } else { "." })).children(children)
}

// Usage: required props go to `new`, optional props are builder methods,
// children use the familiar `.child(..)`.
let greeting = Greeting::new("Ada").excited(true).on_wave(|_, _, _| {}).child("Welcome back");

Parameter rules:

  • A parameter named window or cx receives the GPUI window or app context. cx: &mut Cx receives both as one Cx handle instead (then there is no window parameter).
  • Plain parameters are required props and become arguments of new(..) (taking impl Into<T>).
  • #[default] parameters start at Default::default(), #[default(expr)] ones at expr, and get a builder method with the same name. For Option<T> the method takes impl Into<T>. #[prop(optional)] is the older spelling of #[default].
  • Props of type EventHandler<E> (or Option<EventHandler<E>>) take a closure Fn(&E, &mut Window, &mut App) directly.
  • One #[children] parameter of type Vec<AnyElement> makes the component a ParentElement, so .child(..) and .children(..) work.
  • One #[style] parameter of type StyleRefinement makes the component Styled, so callers can chain .w_full(), .mt_4(), … like a className. Apply it in the body with .apply_style_overrides(&style_overrides).
  • One #[sx] sx: Sx parameter makes the component accept .sx(..) styles (StyleX’s xstyle). Apply them last in the body: .sx((&MY_STYLES.base, &sx)).