sycamore_web/noderef.rs
1//! References to nodes in views.
2//!
3//! This allows imperatively accessing the node.
4//!
5//! You can create a [`NodeRef`] by using [`create_node_ref`].
6
7use std::fmt;
8
9use crate::*;
10
11/// A reference to a [`web_sys::Node`].
12/// This allows imperative access to the node.
13///
14/// # Example
15/// ```
16/// # use sycamore::prelude::*;
17/// #[component]
18/// fn Component() -> View {
19/// let div_ref = create_node_ref();
20/// view! {
21/// div(ref=div_ref)
22/// }
23/// }
24/// ```
25#[derive(PartialEq, Eq, Clone, Copy)]
26pub struct NodeRef(Signal<Option<web_sys::Node>>);
27
28impl NodeRef {
29 /// Alias to [`create_node_ref`].
30 pub fn new() -> Self {
31 create_node_ref()
32 }
33
34 /// Gets the raw node stored inside the node ref.
35 ///
36 /// This attempts to cast the node to the specified type.
37 ///
38 /// # Example
39 /// Node refs are generally meant to be accessed in callbacks or in `on_mount`. Accessing the
40 /// node ref directly in the body of the component will panic because the node ref has not yet
41 /// been set.
42 ///
43 /// ```
44 /// # use sycamore::prelude::*;
45 /// # fn Component() -> View {
46 /// let div_ref = create_node_ref();
47 /// on_mount(move || {
48 /// let node = div_ref.get();
49 /// });
50 /// view! {
51 /// div(ref=div_ref)
52 /// }
53 /// # }
54 /// ```
55 ///
56 /// # Panics
57 /// Panics if the node ref is not set yet or is the wrong type.
58 ///
59 /// For a non panicking version, see [`NodeRef::try_get`].
60 #[track_caller]
61 pub fn get(&self) -> web_sys::Node {
62 self.try_get().expect("NodeRef is not set")
63 }
64
65 /// Tries to get the raw web_sys node stored inside the node ref. Returns `None` if the node
66 /// ref has not yet been set (i.e. the node has not yet been rendered into the DOM).
67 pub fn try_get(&self) -> Option<web_sys::Node> {
68 self.0.get_clone()
69 }
70
71 /// Sets the node ref with the specified node.
72 ///
73 /// This method should be rarely used. Instead, use the `ref=` syntax in the `view!` macro to
74 /// set the node.
75 ///
76 /// # Example
77 /// Setting the node using the `ref=` syntax:
78 /// ```
79 /// # use sycamore::prelude::*;
80 /// #[component]
81 /// fn Component() -> View {
82 /// let div_ref = create_node_ref();
83 /// view! {
84 /// div(ref=div_ref) // This assigns the node ref a value.
85 /// }
86 /// }
87 /// ```
88 pub fn set(&self, node: Option<web_sys::Node>) {
89 self.0.set(node);
90 }
91}
92
93impl Default for NodeRef {
94 fn default() -> Self {
95 Self::new()
96 }
97}
98
99impl fmt::Debug for NodeRef {
100 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101 f.debug_tuple("NodeRef").field(&self.0.get_clone()).finish()
102 }
103}
104
105/* Hook implementation */
106
107/// Create a new [`NodeRef`].
108///
109/// The node ref does not point to anything until it is set, either by assigning it to a node in the
110/// view or by explicitly calling [`NodeRef::set`].
111///
112/// # Example
113/// ```
114/// # use sycamore::prelude::*;
115/// # fn Component() -> View {
116/// let node_ref: NodeRef = create_node_ref();
117/// # view! {}
118/// # }
119/// ```
120pub fn create_node_ref() -> NodeRef {
121 NodeRef(create_signal(None))
122}