Skip to content

Integrate use_ref with NodeRef #1642

@ranile

Description

@ranile

This was initially posted in #1129. This issue tracks its progress.

I'd love to have what @jstarry meant by this "integration" explained here because as it stands, use_ref works well with NodeRef. Example:

#[function_component(UseRef)]
fn ref_hook() -> Html {
    let (outer_html, set_outer_html) = use_state(|| "".to_string());

    let node_ref = use_ref(|| NodeRef::default());

    let on_click = {
        let node_ref = Rc::clone(&node_ref);

        Callback::from(move |e| {
            let to_set = (*node_ref.borrow().deref())
                .cast::<yew::web_sys::Element>()
                .unwrap()
                .outer_html();
            set_outer_html(to_set)
        })
    };
    html! {
        <>
            <div id="result" ref=(*node_ref.borrow_mut().deref_mut()).clone()>{ "Filler" }</div>
            {outer_html}
            <br />
            <button onclick=on_click>{"Refresh"}</button>
        </>
    }
}

Here's the output displayed after clicking on "Refresh" button:
image

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-yewArea: The main yew crate

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions