Fixing "Duplicate Key" Errors in React Trees
When building tree structures in React, you might see this warning:
"Encountered two children with the same key..."
This usually happens when your component is rendering a list or tree and uses the same key
value for multiple items. React requires that keys be unique among siblings to correctly track changes.
The Problem
In some apps, a tree of items is built using IDs like id
, targetId
, and parentId
. A common mistake is using a field like targetId
as the unique key — but if that field isn't truly unique, React throws an error.
Also, when building the tree structure, developers often assume that parentId
matches a node’s id
, but sometimes it actually matches others like targetId
— and since targetId
isn't unique, that causes lookup problems.
The Fix
Here’s how to correctly build the tree and avoid duplicate keys:
- Use
id
as the unique key — it's meant to be unique and stable. - Create a dictionary keyed by
id
. - Build a helper map from
targetId
to nodes — sincetargetId
isn't unique, store an array of nodes pertargetId
. - When assigning children, match
parentId
to the correspondingtargetId
, and attach the node to all matches (if multiple).
Here’s a simplified version of the corrected tree builder:
function buildTree(nodes) {
const updatedNodes = nodes.map(node => ({
...node,
id: String(node.id),
targetId: String(node.targetId),
parentId: String(node.parentId),
children: [],
}));
const targetIdToNodes = {};
updatedNodes.forEach(node => {
if (!targetIdToNodes[node.targetId]) {
targetIdToNodes[node.targetId] = [];
}
targetIdToNodes[node.targetId].push(node);
});
const rootNodes = [];
updatedNodes.forEach(node => {
if (node.parentId === '0') {
rootNodes.push(node);
} else {
const parents = targetIdToNodes[node.parentId];
if (parents) {
parents.forEach(parent => {
parent.children.push(node);
});
}
}
});
return rootNodes;
}
In your React rendering, always use node.id
for the key
:
<TreeNode key={node.id} node={node} />
Takeaway
Always make sure your keys in React are unique and stable. And when building a tree, know what your parentId
is pointing to — it can make or break your structure.
Comments