This is unreleased documentation for Yew Next version.
For up-to-date documentation, see the latest version on docs.rs.

Function yew::functional::use_node_ref

source ·
pub fn use_node_ref<'hook>() -> impl 'hook + Hook<Output = NodeRef>
Expand description

This hook is used for obtaining a NodeRef. It persists across renders.

The ref attribute can be used to attach the NodeRef to an HTML element. In callbacks, you can then get the DOM Element that the ref is attached to.

Example

use wasm_bindgen::prelude::Closure;
use wasm_bindgen::JsCast;
use web_sys::{Event, HtmlElement};
use yew::{function_component, html, use_effect_with_deps, use_node_ref, Html};

#[function_component(UseNodeRef)]
pub fn node_ref_hook() -> Html {
    let div_ref = use_node_ref();

    {
        let div_ref = div_ref.clone();

        use_effect_with_deps(
            |div_ref| {
                let div = div_ref
                    .cast::<HtmlElement>()
                    .expect("div_ref not attached to div element");

                let listener = Closure::<dyn Fn(Event)>::wrap(Box::new(|_| {
                    web_sys::console::log_1(&"Clicked!".into());
                }));

                div.add_event_listener_with_callback(
                    "click",
                    listener.as_ref().unchecked_ref(),
                )
                .unwrap();

                move || {
                    div.remove_event_listener_with_callback(
                        "click",
                        listener.as_ref().unchecked_ref(),
                    )
                    .unwrap();
                }
            },
            div_ref,
        );
    }

    html! {
        <div ref={div_ref}>
            { "Click me and watch the console log!" }
        </div>
    }
}

Tip

When conditionally rendering elements you can use NodeRef in conjunction with use_effect_with_deps to perform actions each time an element is rendered and just before the component where the hook is used in is going to be removed from the DOM.

Note

When used in function components and hooks, this hook is equivalent to:

pub fn use_node_ref() -> NodeRef {
    /* implementation omitted */
}