read_size.rs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. //! Read the size of elements using the MountedData struct.
  2. //!
  3. //! Whenever an Element is finally mounted to the Dom, its data is available to be read.
  4. //! These fields can typically only be read asynchronously, since various renderers need to release the main thread to
  5. //! perform layout and painting.
  6. use std::rc::Rc;
  7. use dioxus::{html::geometry::euclid::Rect, prelude::*};
  8. fn main() {
  9. LaunchBuilder::desktop()
  10. .with_cfg(
  11. dioxus::desktop::Config::default().with_custom_head(
  12. r#"
  13. <style type="text/css">
  14. html, body {
  15. height: 100%;
  16. width: 100%;
  17. margin: 0;
  18. }
  19. #main {
  20. height: 100%;
  21. width: 100%;
  22. }
  23. </style>
  24. "#
  25. .to_owned(),
  26. ),
  27. )
  28. .launch(app);
  29. }
  30. fn app() -> Element {
  31. let mut div_element = use_signal(|| None as Option<Rc<MountedData>>);
  32. let mut dimensions = use_signal(Rect::zero);
  33. let read_dims = move |_| async move {
  34. let read = div_element.read();
  35. let client_rect = read.as_ref().map(|el| el.get_client_rect());
  36. if let Some(client_rect) = client_rect {
  37. if let Ok(rect) = client_rect.await {
  38. dimensions.set(rect);
  39. }
  40. }
  41. };
  42. rsx!(
  43. div {
  44. width: "50%",
  45. height: "50%",
  46. background_color: "red",
  47. onmounted: move |cx| div_element.set(Some(cx.data())),
  48. "This element is {dimensions():?}"
  49. }
  50. button { onclick: read_dims, "Read dimensions" }
  51. )
  52. }