I have a component with a method to add/create a new sub-component and insert it into an array at a specific index (i.e. [elem1, elem2, elem3] becomes [elem1, elem2, new elem, elem3]).
When using something like array.splice(currentIndex + 1, 0, newElement), in the DOM the last element that already exists is just duplicated, though it appears to update correctly for the array in state.
The only way I have found that works is to just use array.push(newElement), which does render properly but is not the desired effect. I've tried a few more ways of inserting the new element into the array but so far everything other than .push() causes the duplication issue. Any suggestions or tips would be greatly appreciated!
const Notef = ({ fetchedParts }) => {
const [parts, setParts] = useState(fetchedParts);
const addNewPart = (currentPart) => {
const index = parts.map((p) => p.id).indexOf(currentPart.id);
const updatedParts = [...parts];
const newPart = { id: pid(), html: 'Type here...', tag: 'p' }
// This will cause duplicated element
updatedParts.splice(index + 1, 0, newPart);
// This does not create duplicate
//updatedParts.push(newPart);
setParts(updatedParts);
}
return (
<>
{parts.map((part) => {
const position = parts.map((p) => p.id).indexOf(part.id) + 1;
return (
<Part
key={part.id}
position={position}
id={part.id}
tag={part.tag}
html={part.html}
addPart={addNewPart}
/>
);
})}
</>
);
}
export default Notef;
Element duplication w/ .splice()
edit: re-worded intro to specify new element to be inserted rather than replaced.
Dominic found the issue - I was using indices for keys in the rendered component. Replaced that with the ID and it solved the issue!
return (
<>
{parts.map((part) => {
const position = parts.map((p) => p.id).indexOf(part.id) + 1;
return (
<Part
key={part.id}
position={position}
id={part.id}
tag={part.tag}
html={part.html}
addPart={addNewPart}
/>
);
})}
</>
);