Skip to content

Commit

Permalink
Better <select> example
Browse files Browse the repository at this point in the history
  • Loading branch information
gbj authored Dec 30, 2023
1 parent 5504283 commit a92293f
Showing 1 changed file with 47 additions and 4 deletions.
51 changes: 47 additions & 4 deletions src/view/05_forms.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,15 +176,58 @@ in Leptos (or vanilla JavaScript) it won’t work.
Instead, use the `selected` field:

```rust
let (value, set_value) = create_signal("B".to_string());
view! {
<select>
<option selected=move || count.get() == 0>"0"</option>
<option selected=move || count.get() == 1>"1"</option>
<option selected=move || count.get() == 2>"2"</option>
<select on:change=move |ev| {
let new_value = event_target_value(&ev);
set_value(new_value);
}>
<option
value="A"
selected=move || value() == "A"
>
"A"
</option>
<option
value="B"
selected=move || value() == "B"
>
"B"
</option>
</select>
}
```

That's somewhat repetitive, but can easily be refactored:
```rust
#[component]
pub fn App() -> impl IntoView {
let (value, set_value) = create_signal("B".to_string());
view! {
<select on:change=move |ev| {
let new_value = event_target_value(&ev);
set_value(new_value);
}>
<SelectOption value is="A"/>
<SelectOption value is="B"/>
<SelectOption value is="C"/>
</select>
}
}

#[component]
pub fn SelectOption(is: &'static str, value: ReadSignal<String>) -> impl IntoView {
view! {
<option
value=is
selected=move || value() == is
>
{is}
</option>
}
}
```

[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/5-forms-0-5-rf2t7c?file=%2Fsrc%2Fmain.rs%3A1%2C1)

<iframe src="https://codesandbox.io/p/sandbox/5-forms-0-5-rf2t7c?file=%2Fsrc%2Fmain.rs%3A1%2C1" width="100%" height="1000px" style="max-height: 100vh"></iframe>
Expand Down

0 comments on commit a92293f

Please sign in to comment.