-
So I've been working on a birthdate selector component where each part (year, month, day) is a #[component]
fn BirthYearSelector(birth_year: RwSignal<u16>) -> impl IntoView {
let current_year = chrono::Local::now().date_naive().year();
// The oldest person alive lived 122 years, so the minimum acceptable date is 122 years back from now
let min_year = current_year - 122;
view! {
<Select val=birth_year>
{(min_year..=current_year)
.map(|year| view! { <option value=year>{year}</option> })
.collect_view()}
</Select>
}
}
#[component]
fn BirthMonthSelector(birth_month: RwSignal<u8>) -> impl IntoView {
view! {
<Select val=birth_month>
{(1..12).map(|month| view! { <option value=month>{month}</option> }).collect_view()}
</Select>
}
}
#[component]
fn BirthDaySelector(
birth_year: RwSignal<u16>,
birth_month: RwSignal<u8>,
birth_day: RwSignal<u8>,
) -> impl IntoView {
let days_in_month = move || {
with!(|birth_year, birth_month| {
chrono::NaiveDate::from_ymd_opt(*birth_year as i32, *birth_month as u32, 1)
.unwrap()
.days_in_month()
})
};
create_effect(move |_| {
tracing::info!(
"year: {}, month: {}, day: {}",
birth_year.get(),
birth_month.get(),
birth_day.get()
)
});
view! {
<Select val=birth_day>
{move || {
(1..=days_in_month())
.map(|day| view! { <option value=day>{day}</option> })
.collect_view()
}}
</Select>
}
} There is also a helper #[component]
fn Select<T>(val: RwSignal<T>, children: Children) -> impl IntoView
where
T: Display + FromStr + Clone + 'static,
<T as FromStr>::Err: std::fmt::Debug,
wasm_bindgen::JsValue: std::convert::From<T>,
{
view! {
<select
prop:value=val
on:change=move |ev| val.set(event_target_value(&ev).parse().unwrap())
>
{children()}
</select>
}
} And the whole thing is used like this: view! {
<label>Birthdate</label>
<fieldset>
<BirthYearSelector birth_year=passenger.birth_year/>
<BirthMonthSelector birth_month=passenger.birth_month/>
<BirthDaySelector
birth_year=passenger.birth_year
birth_month=passenger.birth_month
birth_day=passenger.birth_day
/>
</fieldset>
} I think there must be some very basic thing I may be missing but I'm still too much of a beginner in leptos |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
I'm going to guess your issue here is that every time the number of items changes, it rerenders all the I'm talking about things like this in case it's not clear {move || {
(1..=days_in_month())
.map(|day| view! { <option value=day>{day}</option> })
.collect_view()
}} |
Beta Was this translation helpful? Give feedback.
-
It was exactly that! Thank you, Greg! |
Beta Was this translation helpful? Give feedback.
I'm going to guess your issue here is that every time the number of items changes, it rerenders all the
<option>
elements, and that unmounting and remounting those all resets the value in the<select>
, but I'm not sure. Maybe try a keyed list with<For/>
rather than the unkeyed iteration you're doing at present.I'm talking about things like this in case it's not clear