React: ref={???????????}

I read and reread docs and tutorials about "ref", but they never quite connected with my general knowledge of JavaScript. So I did more digging and here's what I found:

Ref's are a way to get a reference to an actual HTML DOM node that was generated by React. (They can also get a reference to a React component instance, but I'm not going there today.)

React.createRef() just returns a new object like {current:null}. So I assume that's what a ref looks like.

From looking at examples... when some element includes an attribute called "ref", like this:

<foo ref={expression_that_evaluates_to_a_ref}     />

...then the JSX is compiled into some JavaScript which assigns a reference to the foo DOM node to the "current" property of that ref object. So we use this by calling React.createRef() and putting a reference to the ref object somewhere where we will be able to get it later. Then after render() runs and our ref object's "current" property has been pointed to a DOM node, we can manipulate that DOM node.

OR, as docs do clearly say, if we instead do:

<foo ref={expression_that_evaluates_to_a_function}     />

...then that function is called with the DOM node as it's argument.

AND we see from examples that we can use a function literal as expression_that_evaluates_to_a_function. And then that function literal is embedded in the vanilla JavaScript that was compiled from the JSX in render() and has that scope. So we can do...

<foo ref={(element)=>{.....closure-ness..and..other..fun..with..that..scope........}}

...and interact with other stuff in the compiled render function's scope.

It's generally agreed that ref's shouldn't be our first choice. And one writer noted that we can aften get a reference to the DOM node from an event object.


Comments

Popular posts from this blog

Callback, Promise, Observable, and Doughnuts

Learn grid and grid-template-areas FIRST!!!

The Day TDD Started Working for Me