mirror of
https://github.com/yewstack/yew.git
synced 2025-12-08 21:26:25 +00:00
* 0.20 Changelog * Improve changelog generator * Add blog post * Add blog post * Apply suggestions from code review Co-authored-by: WorldSEnder <WorldSEnder@users.noreply.github.com> Co-authored-by: Julius Lungys <32368314+voidpumpkin@users.noreply.github.com> * update Changelog * update Cargo.toml * changelog gen compiles * website version 0.20 * add migration guides * prettier * i18n Co-authored-by: WorldSEnder <WorldSEnder@users.noreply.github.com> Co-authored-by: Julius Lungys <32368314+voidpumpkin@users.noreply.github.com>
56 lines
1.4 KiB
Plaintext
56 lines
1.4 KiB
Plaintext
---
|
|
title: 'Refs'
|
|
description: 'Out-of-band DOM access'
|
|
---
|
|
|
|
The `ref` keyword can be used inside of any HTML element or component to get the DOM `Element` that
|
|
the item is attached to. This can be used to make changes to the DOM outside of the `view` lifecycle
|
|
method.
|
|
|
|
This is useful for getting ahold of canvas elements, or scrolling to different sections of a page.
|
|
For example, using a `NodeRef` in a component's `rendered` method allows you to make draw calls to
|
|
a canvas element after it has been rendered from `view`.
|
|
|
|
The syntax is:
|
|
|
|
```rust
|
|
use web_sys::Element;
|
|
use yew::{html, Component, Context, Html, NodeRef};
|
|
|
|
struct Comp {
|
|
node_ref: NodeRef,
|
|
}
|
|
|
|
impl Component for Comp {
|
|
type Message = ();
|
|
type Properties = ();
|
|
|
|
fn create(_ctx: &Context<Self>) -> Self {
|
|
Self {
|
|
// highlight-next-line
|
|
node_ref: NodeRef::default(),
|
|
}
|
|
}
|
|
|
|
fn view(&self, _ctx: &Context<Self>) -> Html {
|
|
html! {
|
|
// highlight-next-line
|
|
<div ref={self.node_ref.clone()}></div>
|
|
}
|
|
}
|
|
|
|
fn rendered(&mut self, _ctx: &Context<Self>, _first_render: bool) {
|
|
// highlight-start
|
|
let has_attributes = self.node_ref
|
|
.cast::<Element>()
|
|
.unwrap()
|
|
.has_attributes();
|
|
// highlight-end
|
|
}
|
|
}
|
|
```
|
|
|
|
## Relevant examples
|
|
|
|
- [Node Refs](https://github.com/yewstack/yew/tree/master/examples/node_refs)
|