scroll_to_top.rs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. //! Scroll elements using their MountedData
  2. //!
  3. //! Dioxus exposes a few helpful APIs around elements (mimicking the DOM APIs) to allow you to interact with elements
  4. //! across the renderers. This includes scrolling, reading dimensions, and more.
  5. //!
  6. //! In this example we demonstrate how to scroll to the top of the page using the `scroll_to` method on the `MountedData`
  7. use dioxus::prelude::*;
  8. fn main() {
  9. dioxus::launch(app);
  10. }
  11. fn app() -> Element {
  12. let mut header_element = use_signal(|| None);
  13. rsx! {
  14. div {
  15. h1 {
  16. onmounted: move |cx| header_element.set(Some(cx.data())),
  17. "Scroll to top example"
  18. }
  19. for i in 0..100 {
  20. div { "Item {i}" }
  21. }
  22. button {
  23. onclick: move |_| async move {
  24. if let Some(header) = header_element.cloned() {
  25. header.scroll_to(ScrollBehavior::Smooth).await.unwrap();
  26. }
  27. },
  28. "Scroll to top"
  29. }
  30. }
  31. }
  32. }