Attach Yew to Different DOM Element
When using Yew, I wanted to attach the app to an element other than body
and this is how I did.
So, the idea is to have Renderer::with_root()
- yew::Renderer::<App>::new().render();
+ yew::Renderer::<App>::with_root(elem).render();
// src/main.rs
mod app;
mod utils;
use crate::utils::get_element_by_id;
use app::App;
fn main() {
match get_element_by_id("container") {
Ok(elem) => {
yew::Renderer::<App>::with_root(elem)
.render();
}
Err(err) => console::log_1(
&(format!("ERR: {}", err).into()),
),
}
}
For get_element_by_id above is a tiny tool of mine which is defined in src/utils.js:
// src/utils.js
pub fn get_element_by_id(
id: &str,
) -> Result<web_sys::Element, String> {
web_sys::window()
.ok_or("No window")
.unwrap()
.document()
.ok_or("No document")
.unwrap()
.get_element_by_id(id)
.ok_or_else(|| {
format!("No element for: {}", id)
})
}
TOP