Refs
ref log gives a name to an element inside the markup, <ul ref={log}>, without taking the element out of it. The element exists from the start of the body: it is created where the ref is declared, with the attributes written as strings, and the markup fills it in. So a ref is never null.
// ref names an element inside the markup: it exists from the start of the body, with the // attributes written as strings, and the markup fills it in comp Chat() { state messages string[] = ["Hi! Write something"] state draft = "" ref log ref input // Runs again after every new message: scrolls the list to the end effect { if messages.length > 0 { log.scrollTop = log.scrollHeight } } // The markup is on the page: the cursor goes into the input mount { input.focus() } func send() { if const trimmed = draft.trim(); trimmed != "" { messages.push(trimmed) draft = "" } input.focus() } return <section class="chat"> <ul class="log" ref={log}> {for message in messages { <li>{message}</li> }} </ul> <form onSubmit={event.preventDefault(); send()}> <input ref={input} bind:value={draft} placeholder="Message" /> <button>Send</button> </form> </section> } document.body.append(<Chat />)
On the board, give the new-task input a ref so mount can focus it when the add form opens. The input stays in the markup; the ref is for the browser operation, not a replacement for the component.
- A ref has the type of its element, here
HTMLUListElement, or the one written:ref log HTMLElement. It cannot be assigned. - Above
returnthe element has its string attributes but no children and no handlers yet; inmount,effectand handlers it is complete. The markup can use an element written further down:<label for={input.id}>before<input id="name" ref={input} />. - A ref points to one element, which the markup creates once. Inside
{if},{for},{switch}and functions the element is created again, so a ref there is a compile error: an element of a list goes into a component with a ref of its own. <Field ref={name} />points to the element at the top of whatFieldreturns, and a decorator binds its refs in the markup of its wrapper.