Here is a simple reproduce of my issue.
Im using Nextjs, react, @dnd-kit/core, typescript.
Normally if I do testRef?.current?.focus(), the input field will have the cursor and if I directly type on keyboard, the value would change.
But in this case I cannot type, but the outline of the input field and the log indicate that the focus is triggered. ONLY THAT I CANNOT Type.
"use client";
import {
DragEndEvent,
useDndMonitor,
useDraggable,
useDroppable,
} from "@dnd-kit/core";
import React, { useRef } from "react";
function page() {
const testRef = useRef(null);
useDndMonitor({
onDragEnd: (event: DragEndEvent) => {
if (testRef.current) {
console.log("focus");
(testRef?.current as HTMLInputElement).focus();
}
},
});
const draggable = useDraggable({
id: "drag",
});
const droppable = useDroppable({
id: "drop",
});
return (
<div>
<div
ref={draggable.setNodeRef}
{...draggable.listeners}
{...draggable.attributes}
className="h-10 w-10 border border-yellow-200"
>
drag
</div>
<div
ref={droppable.setNodeRef}
className="h-10 w-10 border border-green-200"
>
drop
</div>
<form onSubmit={() => console.log("submit")}>
<input ref={testRef} defaultValue={"default "} />
<input type="submit" />
</form>
</div>
);
}
export default page;
I think it is the useDndMonitor makes it weird behind the scene because if it is a button on click listener, it would set the focus just fine.
But the very first of all, I want to know that why the text field is focused but not really (cannot type). Is the focus lost else where after the drag end?
Expect from answers:
- How to make it work (after drop, it set the focus correctly, so that user can type directly)
- The root cause of this issue.
1