Ref

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// variable assigned directly by ref
let myDiv;

// use onMount or createEffect to read after connected to DOM
onMount(() => 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.

1
2
3
4
5
6
7
8
9
function MyComp(props) {
  return <div ref={props.ref} />;
}

function App() {
  let myDiv;
  onMount(() => console.log(myDiv.clientWidth));
  return <MyComp ref={myDiv} />;
}

Комментарии