ref
Refs are a way of getting access to underlying DOM elements in our JSX. While it is true one could just assign an element to a variable, it is more optimal to leave components in the flow of JSX. Refs are assigned at render time but before the elements are connected to the DOM. They come in 2 flavors.
tsx
// variable assigned directly by reflet myDiv;// use onMount or createEffect to read after connected to DOMonMount(() => console.log(myDiv));<div ref={myDiv} />// Or, callback function (called before connected to DOM)<div ref={el => console.log(el)} />
tsx
// variable assigned directly by reflet myDiv;// use onMount or createEffect to read after connected to DOMonMount(() => console.log(myDiv));<div ref={myDiv} />// Or, callback function (called before connected to DOM)<div ref={el => console.log(el)} />
Refs can also be used on Components. They still need to be attached on the other side.
tsx
function MyComp(props) {return <div ref={props.ref} />;}function App() {let myDiv;onMount(() => console.log(myDiv.clientWidth));return <MyComp ref={myDiv} />;}
tsx
function MyComp(props) {return <div ref={props.ref} />;}function App() {let myDiv;onMount(() => console.log(myDiv.clientWidth));return <MyComp ref={myDiv} />;}