From 2edd2a02b3ddd0f0b7b04d0b596892eccfd0bf6c Mon Sep 17 00:00:00 2001 From: Cecile Tonglet Date: Mon, 30 Jan 2023 15:52:58 +0100 Subject: [PATCH] HtmlSelect: make sure selection is updated after render (#163) --- src/html_select.rs | 33 +++++++++++++++++++++------------ 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/src/html_select.rs b/src/html_select.rs index d066d63..1dbb532 100644 --- a/src/html_select.rs +++ b/src/html_select.rs @@ -8,6 +8,7 @@ use yew::prelude::*; #[derive(Debug)] pub struct HtmlSelect { select_element: NodeRef, + update_selected: bool, phantom: PhantomData, } @@ -39,6 +40,7 @@ impl Component for HtmlSelect { fn create(_ctx: &Context) -> Self { Self { select_element: NodeRef::default(), + update_selected: false, phantom: PhantomData, } } @@ -57,18 +59,8 @@ impl Component for HtmlSelect { false } - fn changed(&mut self, ctx: &Context, _old_props: &Self::Properties) -> bool { - if let Some(value) = ctx.props().value.as_ref() { - if let Some(select) = self.select_element.cast::() { - if let Some(i) = ctx.props().options.iter().position(|(x, _)| &x == value) { - if let Ok(i) = i.try_into() { - if select.selected_index() != i { - select.set_selected_index(i); - } - } - } - } - } + fn changed(&mut self, _ctx: &Context, _old_props: &Self::Properties) -> bool { + self.update_selected = true; true } @@ -122,4 +114,21 @@ impl Component for HtmlSelect { } } + + fn rendered(&mut self, ctx: &Context, _first_render: bool) { + if self.update_selected { + self.update_selected = false; + if let Some(value) = ctx.props().value.as_ref() { + if let Some(select) = self.select_element.cast::() { + if let Some(i) = ctx.props().options.iter().position(|(x, _)| &x == value) { + if let Ok(i) = i.try_into() { + if select.selected_index() != i { + select.set_selected_index(i); + } + } + } + } + } + } + } }