Struct NodeRef
pub struct NodeRef(/* private fields */);
Expand description
A reference to a web_sys::Node
.
This allows imperative access to the node.
§Example
#[component]
fn Component() -> View {
let div_ref = create_node_ref();
view! {
div(ref=div_ref)
}
}
Implementations§
§impl NodeRef
impl NodeRef
pub fn new() -> NodeRef
pub fn new() -> NodeRef
Alias to create_node_ref
.
pub fn get(&self) -> Node
pub fn get(&self) -> Node
Gets the raw node stored inside the node ref.
This attempts to cast the node to the specified type.
§Example
Node refs are generally meant to be accessed in callbacks or in on_mount
. Accessing the
node ref directly in the body of the component will panic because the node ref has not yet
been set.
let div_ref = create_node_ref();
on_mount(move || {
let node = div_ref.get();
});
view! {
div(ref=div_ref)
}
§Panics
Panics if the node ref is not set yet or is the wrong type.
For a non panicking version, see NodeRef::try_get
.
pub fn try_get(&self) -> Option<Node>
pub fn try_get(&self) -> Option<Node>
Tries to get the raw web_sys node stored inside the node ref. Returns None
if the node
ref has not yet been set (i.e. the node has not yet been rendered into the DOM).
pub fn set(&self, node: Option<Node>)
pub fn set(&self, node: Option<Node>)
Sets the node ref with the specified node.
This method should be rarely used. Instead, use the ref=
syntax in the view!
macro to
set the node.
§Example
Setting the node using the ref=
syntax:
#[component]
fn Component() -> View {
let div_ref = create_node_ref();
view! {
div(ref=div_ref) // This assigns the node ref a value.
}
}