I was wondering how I could get element attributes in Dioxus in Rust. More specifically, how can I get the element height and width. The CSS uses % instead of px and I want to somehow get the px of the element.
...
div { class: "some_class",
// get div height here
}
...
Thank you for your help in advance!
I am hoping not to have to use JavaScript, but currently I am not sure what support Dioxus has to offer.
From https://github.com/DioxusLabs/dioxus/blob/main/examples/read_size.rs:
Whenever an Element is finally mounted to the Dom, its data is available to be read. These fields can typically only be read asynchronously, since various renderers need to release the main thread to perform layout and painting.
use std::rc::Rc;
use dioxus::{html::geometry::euclid::Rect, prelude::*};
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
// Create a mutable signal to store the MountedData of the div element
let mut div_element = use_signal(|| None as Option<Rc<MountedData>>);
// Create a mutable signal to store the dimensions of the div element
let mut dimensions = use_signal(Rect::zero);
// Define an async closure to read the dimensions
let read_dims = move |_| async move {
// Read the current value of div_element
let read = div_element.read();
// Get the client rectangle from the read data
let client_rect = read.as_ref().map(|el| el.get_client_rect());
// Check if there's a client rectangle
if let Some(client_rect) = client_rect {
// Await the client rectangle
if let Ok(rect) = client_rect.await {
// Set the dimensions signal with the received rectangle
dimensions.set(rect);
}
}
};
rsx!(
document::Link { rel: "stylesheet", href: asset!("./examples/assets/read_size.css") }
div {
width: "50%",
height: "50%",
background_color: "red",
// Set data on mount
onmounted: move |cx| div_element.set(Some(cx.data())),
// Display the current dimensions of the div
"This element is {dimensions():?}"
}
// Add a button to trigger reading dimensions
button { onclick: read_dims, "Read dimensions" }
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With