Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optional attributes in view! #622

Open
smessmer opened this issue Sep 2, 2023 · 0 comments
Open

Optional attributes in view! #622

smessmer opened this issue Sep 2, 2023 · 0 comments
Labels
A-view Area: view! macro C-enhancement Category: new feature or improvement to existing feature
Milestone

Comments

@smessmer
Copy link

smessmer commented Sep 2, 2023

It would be great if the view! macro allowed attributes to be set to an Optional, and then would generate the attribute if and only if the Optional is Some.

Use case:
Let's say we are wrapping a input component into our own Switch component:

#[derive(Prop)]
pub struct SwitchProps<'cx> {
    checked: &'cx Signal<bool>,
    // id can be present or absent
    #[builder(default)]
    id: Option<&'cx str>,
}

#[component]
pub fn Switch<'a, G: Html>(cx: Scope<'a>, props: SwitchProps<'a>) -> View<G> {
    view! {cx,
        input(
            type="checkbox",
            role="switch",
            class="...",
            id=(props.id),
            bind:checked=props.checked,
        )
    }
}

The SwitchProps::id prop will be present or absent depending on whether the call site specified it. But the view! macro currently does not allow it being passed through to input the same way. Instead, we have to write much more verbosely:

#[component]
pub fn Switch<'a, G: Html>(cx: Scope<'a>, props: SwitchProps<'a>) -> View<G> {
    if let Some(id) = props.id {
        view! {cx,
            input(
                type="checkbox",
                role="switch",
                class="...",
                id=id,
                bind:checked=props.checked,
            )
        }
    } else {
        view! {cx,
            input(
                type="checkbox",
                role="switch",
                class="...",
                bind:checked=props.checked,
            )
        }
    }
}
@lukechu10 lukechu10 added A-view Area: view! macro C-enhancement Category: new feature or improvement to existing feature labels Sep 4, 2023
@lukechu10 lukechu10 added this to the v0.9 milestone Sep 5, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-view Area: view! macro C-enhancement Category: new feature or improvement to existing feature
Projects
None yet
Development

No branches or pull requests

2 participants