'Refs from Class Component to Functional Component

I am in the process of converting a file from a class component to a functional component.

let embellishmentRefs = createRef<AddArtEmbellishmentEntry>();

useEffect(() => {
        const embellishments = Object.assign([], props.orderLinesDetailed[0].embellishments);

        embellishments.forEach((embellishment, i) => {
            embellishment.Id = i;
            const ref: React.RefObject<AddArtEmbellishmentEntry> = React.createRef();
            embellishmentRefs.push(ref);
        });
    })

I am however getting stuck on how I should refactor this:

const ref: React.RefObject<AddArtEmbellishmentEntry> = React.createRef();
embellishmentRefs.push(ref);

Any tips?



Solution 1:[1]

From what I can tell of the code in your question, it appears you are trying to create an array of React refs. You will need to use the useRef hook to store the array of the other refs you are creating. From here, each render cycle map over the embellishments array and create a React ref if one hasn't already been created, and set the current embellishmentRefs value with the mapped array.

Example:

const embellishmentRefs = React.useRef<AddArtEmbellishmentEntry[]>([]);

const embellishments = Object.assign(
  [],
  props.orderLinesDetailed[0].embellishments
);

embellishmentRefs.current = embellishments.map(
  (_, i) => 
    embellishmentRefs.current[i] ?? React.createRef<AddArtEmbellishmentEntry>()
);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1