Ref
it helps to preserve values between component re-rendering, besides of allowing interactions with DOM elements
Preserving values
import { Component, html } from 'vistajs/dom';
import { bootstrap } from 'vistajs/boot';
Component('app-child', () => {
const buttonRef = ref(1, 'myRef');
const changeRef = () => {
buttonRef.current = buttonRef.current + 1;
};
return () => html`
<button onclick="${changeRef()}">
${buttonRef.current}
</button>
`;
});
const App = Component('app-parent', () => {
const count = signal(0);
return () => html`
<div>
<app-child />
<div>
<button onclick="${() => count.set(count() + 1)}">
${count()}
</button>
</div>
</div>
`;
});
const root = document.querySelector('#root') as Element;
bootstrap(root, App)In the previous code snippet, both components are going to render the counter at 0 the first rendering
When app-child component counter value is incremented by clicking the button, we are goin to have rendered:
Then, by clicking respective app-parent counter button, we are going to have component value updated in the template, however, app-child will holds its value, rendering:
That's what ref is used for, without it, the standard behavior would use app-child declared initial value and render in the component's template.
Manipulating DOM
Ref is also useful for manipulating DOM elements without dispatch re-rendering, ref holds element reference which allows you to interect with it as if would making with with standard DOM API
When button is clicked input field will get focused. We can go further as with ref we get straight access to DOM elements
Last updated