Right now I am learning with drag and drop event. And there is a case that I need to update the text in drag image when I drag to specific div
export const DndPage = () => {
const handleOnDrag = useCallback((event) => {
const ghost = document.getElementById('ghost');
event.dataTransfer.effectAllowed = 'copy';
event.dataTransfer.setDragImage(ghost, 0, 0);
event.dataTransfer.setData('text', 'text');
}, []);
const [text, setText] = useState('');
const [dragText, setDragText] = useState('');
const renderItemToDrag = useCallback(
(text: string) => {
return (
<>
<div
id='drag-zone'
draggable
onDragStart={handleOnDrag}
style={{
border: '1px solid black',
padding: '10px',
width: '50%',
marginBottom: '10px',
}}
>
<span>{text}</span>
</div>
<div
id='ghost'
style={{
position: 'absolute',
top: '-1000px',
width: '100px',
height: '30px',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
textAlign: 'center',
}}
>
Copy to {dragText}
</div>
</>
);
},
[dragText]
);
return (
<>
{renderItemToDrag('this is a draggable')}
<div
id='drop-zone'
onDrop={(e) => {
const data = e.dataTransfer.getData('text');
setText(data);
}}
onDragOver={(e) => {
e.dataTransfer.dropEffect = 'none';
if ((e.target as HTMLElement).className === 'infomation') {
e.dataTransfer.dropEffect = 'copy';
setDragText('infomation');
}
e.preventDefault();
}}
style={{
display: 'flex',
flexDirection: 'column',
gap: '10px',
width: '400px',
}}
>
<h3 className='infomation'>Drop area</h3>
<span
style={{ border: '1px solid black', padding: '10px', width: '200px' }}
>
{text}
</span>
</div>
</>
);
};
As you can see, my function onDragOver
get innerText
of element and setDragText(value)
to display on my ghost drag image (id="ghost"
).
But it does not update? Can somebody explain why? I try to use ref but it does not work neither