Why is necessary to know how to make dynamic the useRef
hook?
Well, is necessary for different reasons for example, sometimes we have components that are created by iterations, and we need to have a reference to access the properties of the element.
export default function Component() {
const list = ["one item", "other item"];
const accordion = useRef();
return list.map((item) => (
<Accordion title="Something" ref={accordion}>
<p>{item}</p>
</Accordion>
));
}
The code above will not work because we are referencing all the items in the iterations with the same ref
, but how to solve it? Is not as complicated as you may think.
First we have to be aware of the function createRef()
. The rest is very simple but let's code to have a better explanation.
export default function Component() {
const list = ["one item", "other item"];
const elementsRef = useRef(list.map(() => createRef()));
return list.map((item,index) => (
<Accordion title="Something" ref={elementsRef.current[index]}>
<p>{item}</p>
</Accordion>
));
}
The difference between the first and second code is line number 3, where we solve the ref
creating a list of references with the size of our list, then when we are using the ref into the component is just as simple as accessing the current property of the variable elementsRef and get the ref with the index of the iteration.
Top comments (0)