I am making a drag and drop system with react dnd. In the drag section the unique id is generated while dragging item:{id:uuid(),type:type}
the item the element and on drop the item is received in drop section
const [,drop] = useDrop(()=>({
accept:Object.values(dragAbleTypes),
drop:(item:{id:UUIDTypes,type:string}, monitor)=>{
console.log(item.id);
On first drag and drop it generate the id. when i do it for second time it’s giving me this error. Also while i log the id console.log(item.id);
the same id is loging every time which is generated at the first drag & drop
<div className='h-screen flex flex-col border w-full 'ref={drop}>
{elements.map(e=>{
console.log("key:",e.id);
return(<EditorRenderingHelper key={e.id.toString()} element = {e}/>)
})}
the logs:
key: 98f499f3-f214-401d-90ce-a069c7396a34
key: 98f499f3-f214-401d-90ce-a069c7396a34
key: 98f499f3-f214-401d-90ce-a069c7396a34
key: 98f499f3-f214-401d-90ce-a069c7396a34
The browser console is showing this,
Encountered two children with the same key, `f1ff56c1-0b2e-4f4c-9ba5-6c1568714635`. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.
The component codes,
drag component
function DragElements({type}:{
type:typeof dragAbleTypes[keyof typeof dragAbleTypes]}) {
const [{isdragging},drag] = useDrag(()=>({
type:type,
item:{id:uuid(),type:type},
collect:(e)=>{
return {isdragging:!!e.isDragging()}
}
}))
return (
// @ts-ignore
<div ref={drag}>
{type}
</div>
)
}
export default DragElements
drop component
function Canvas() {
const [elements, setElements] = useAtom(editorState)
const [,drop] = useDrop(()=>({
accept:Object.values(dragAbleTypes),
drop:(item:{id:UUIDTypes,type:string}, monitor)=>{
console.log(item.id);
const newElement = {
id:item.id,
type:item.type
}
setElements(e=>e = [...e,newElement])
}
}))
return (
// @ts-ignore
<div className='h-screen flex flex-col border w-full 'ref={drop}>
{elements.map(e=>{
return(<EditorRenderingHelper key={e.id.toString()} element = {e}/>)
})}
</div>
)
}
export default Canvas