I am trying to build a simple to-do list where each task can be edited by clicking on edit button which shows a previously hidden text field in which user can enter new name for the current task, for this I need to assign a ref value to each task so far I have tried
let refrences = useRef([]);
//this is within a array.map method
<input type='text' ref={refrences.current[index]} />
//some code here
But refrences.current[index] always shows as undefined and I have no idea why that’s the case but when I try the following(found it online)
let refrences = useRef([]);
//this is within a array.map method
<input type='text' ref={element => refrences.current[index]=element} />
//some code here
This works perfectly fine but I have no idea why this works. I know this is an arrow function but I can’t tell what the ‘element’ stands for even though it has not been defined anywhere else. Any help would be appreciated
2
Answers
To the best of my knowledge you can pass at least two kinds of values to the
ref
pop:useRef
React DocsReference object
As you already know,
useRef
returns an object with acurrent
property. When you pass that object to theref
prop, React can assign the DOM element to that property, i.e. something like(to be honest I don’t know if React requires the
current
property to be present. It might as well always assign to thecurrent
property if the passed value is an object)Function
If you pass a function however, React will call that function with the DOM element passed as argument, something like:
In your code
element
is a parameter of the function you pass toref
. It works like any other (callback) function. The caller of the function, in this case React, will provide a value for that argument.It’s essentially the same as for example
Array#forEach
and other higher level functions:In this example you pass a function to
forEach
that has a single parameteri
. The JavaScript engine will call that function for every element in the array and pass that element to the function (which therefore gets assigned to the parameteri
).Why does
ref={refrences.current[index]}
not work?The value of
reference.current[index]
is not a "reference object". It’s not an object with acurrent
property, so React cannot executeref.current = element
in fact, known as "using callback refs"
by passing a callback to the ref, you get more granular control on binding a DOM element to the react ref object.
you provide a callback and your current element which you have added ref props on it will be pass as element argument by react,
so if you have an index, you know which position of reference array it should be placed and you also have a DOM reference using Element so you could capture it on your loop.