Mr. Robot
Mr. Robot

Reputation: 1824

Empty items being added to array of refs in React

I have the following code:

const nodeRefs = useRef<Array<HTMLDivElement | null>>([]);

function setNodeRefs(ref: HTMLDivElement | null, idx: number): void { nodeRefs.current[idx] = ref; }

{nodes.length === 5 && nodes.map((node, idx) => (idx === 1 || idx === 2)
    && (
        <MyComponent
            setNodeRefs={setNodeRefs}
            idx={idx}
            key={String(`${idx}-${uuidv4()}`)}
            className="h__node"
        />
    ))}

However the resulting array of refs includes an empty item:

[empty, div.h__node, div.h__node]

It seems like a node is being set in the array of refs even when the condition inside the map is not met.

How can I create the array without adding the empty item to it?

Upvotes: 0

Views: 677

Answers (2)

Someone Special
Someone Special

Reputation: 13588

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

Hence even though you have conditions, the size of the array will remain unchanged when you use .map. You may want to use .forEach or for-loops.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Upvotes: 0

jaibatrik
jaibatrik

Reputation: 7533

This is happening because you are setting the elements at indices 1 and 2 respectively, and the 0th index of your nodeRefs.current array is undefined.

Depending on your requirement, subtracting 1 from idx or using Array#push should do.

Upvotes: 2

Related Questions