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
To the best of my knowledge you can pass at least two kinds of values to the
refpop:useRefReact DocsReference object
As you already know,
useRefreturns an object with acurrentproperty. When you pass that object to therefprop, React can assign the DOM element to that property, i.e. something like(to be honest I don't know if React requires the
currentproperty to be present. It might as well always assign to thecurrentproperty 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
elementis 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#forEachand other higher level functions:In this example you pass a function to
forEachthat 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 acurrentproperty, so React cannot executeref.current = element