diff --git a/crates/story/src/radio_story.rs b/crates/story/src/radio_story.rs index f710d984..63fbbb53 100644 --- a/crates/story/src/radio_story.rs +++ b/crates/story/src/radio_story.rs @@ -104,7 +104,7 @@ impl Render for RadioStory { ) .child( section("Radio Group").max_w_md().child( - RadioGroup::horizontal() + RadioGroup::horizontal("radio_group_1") .children(["One", "Two", "Three"]) .selected_index(self.radio_group_checked) .on_change(cx.listener(|this, selected_ix: &usize, _, cx| { @@ -117,7 +117,7 @@ impl Render for RadioStory { section("Radio Group Vertical (With container style)") .max_w_md() .child( - RadioGroup::vertical() + RadioGroup::vertical("radio_group_2") .w(px(220.)) .p_2() .border_1() @@ -127,11 +127,7 @@ impl Render for RadioStory { .child(Radio::new("one1").label("United States")) .child(Radio::new("one2").label("Canada")) .child(Radio::new("one3").label("Mexico")) - .selected_index(self.radio_group_checked) - .on_change(cx.listener(|this, selected_ix: &usize, _, cx| { - this.radio_group_checked = Some(*selected_ix); - cx.notify(); - })), + .selected_index(Some(1)), ), ) } diff --git a/crates/ui/src/radio.rs b/crates/ui/src/radio.rs index 4776148b..14800b6a 100644 --- a/crates/ui/src/radio.rs +++ b/crates/ui/src/radio.rs @@ -146,6 +146,7 @@ impl RenderOnce for Radio { /// A Radio group element. #[derive(IntoElement)] pub struct RadioGroup { + id: ElementId, style: StyleRefinement, radios: Vec, layout: Axis, @@ -155,8 +156,9 @@ pub struct RadioGroup { } impl RadioGroup { - fn new() -> Self { + fn new(id: impl Into) -> Self { Self { + id: id.into(), style: StyleRefinement::default().flex_1(), on_change: None, layout: Axis::Vertical, @@ -167,13 +169,13 @@ impl RadioGroup { } /// Create a new Radio group with default Vertical layout. - pub fn vertical() -> Self { - Self::new() + pub fn vertical(id: impl Into) -> Self { + Self::new(id) } /// Create a new Radio group with Horizontal layout. - pub fn horizontal() -> Self { - Self::new().layout(Axis::Horizontal) + pub fn horizontal(id: impl Into) -> Self { + Self::new(id).layout(Axis::Horizontal) } /// Set the layout of the Radio group. Default is `Axis::Vertical`. @@ -249,14 +251,15 @@ impl RenderOnce for RadioGroup { h_flex().w_full().flex_wrap() }; - let mut container = div(); + let mut container = div().id(self.id); *container.style() = self.style; container.child( base.gap_3() - .children(self.radios.into_iter().enumerate().map(|(ix, radio)| { + .children(self.radios.into_iter().enumerate().map(|(ix, mut radio)| { let checked = selected_ix == Some(ix); + radio.id = ix.into(); radio.disabled(disabled).checked(checked).when_some( on_change.clone(), |this, on_change| {