You are currently viewing the docs for Dioxus 0.3.2 which is no longer maintained.

Component Children

In some cases, you may wish to create a component that acts as a container for some other content, without the component needing to know what that content is. To achieve this, create a prop of type Element:

src/component_element_props.rs
#[derive(Props)]
struct ClickableProps<'a> {
    href: &'a str,
    body: Element<'a>,
}

fn Clickable<'a>(cx: Scope<'a, ClickableProps<'a>>) -> Element {
    cx.render(rsx!(
        a {
            href: "{cx.props.href}",
            class: "fancy-button",
            &cx.props.body
        }
    ))
}

Then, when rendering the component, you can pass in the output of cx.render(rsx!(...)):

src/component_element_props.rs
cx.render(rsx! {
    Clickable {
        href: "https://www.youtube.com/watch?v=C-M2hs3sXGo",
        body: cx.render(rsx!("How to " i {"not"} " be seen")),
    }
})

Note: Since Element<'a> is a borrowed prop, there will be no memoization.

Warning: While it may compile, do not include the same Element more than once in the RSX. The resulting behavior is unspecified.

The children field

Rather than passing the RSX through a regular prop, you may wish to accept children similarly to how elements can have children. The "magic" children prop lets you achieve this:

src/component_children.rs
#[derive(Props)]
struct ClickableProps<'a> {
    href: &'a str,
    children: Element<'a>,
}

fn Clickable<'a>(cx: Scope<'a, ClickableProps<'a>>) -> Element {
    cx.render(rsx!(
        a {
            href: "{cx.props.href}",
            class: "fancy-button",
            &cx.props.children
        }
    ))
}

This makes using the component much simpler: simply put the RSX inside the {} brackets – and there is no need for a render call or another macro!

src/component_children.rs
cx.render(rsx! {
    Clickable {
        href: "https://www.youtube.com/watch?v=C-M2hs3sXGo",
        "How to " i {"not"} " be seen"
    }
})