-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Card.tsx
51 lines (46 loc) · 1.18 KB
/
Card.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { CSSProperties, FC, memo, useMemo, useRef } from 'react'
import { useDrag, useDrop } from 'react-dnd'
import { ItemTypes } from './ItemTypes'
const style: CSSProperties = {
border: '1px dashed gray',
padding: '0.5rem 1rem',
marginBottom: '.5rem',
backgroundColor: 'white',
cursor: 'move',
}
export interface CardProps {
id: any
text: string
moveCard: (draggedId: string, id: string) => void
}
export const Card: FC<CardProps> = memo(function Card({ id, text, moveCard }) {
const ref = useRef(null)
const [{ isDragging, handlerId }, connectDrag] = useDrag({
type: ItemTypes.CARD,
item: { id },
collect: (monitor) => {
const result = {
handlerId: monitor.getHandlerId(),
isDragging: monitor.isDragging(),
}
return result
},
})
const [, connectDrop] = useDrop({
accept: ItemTypes.CARD,
hover({ id: draggedId }: { id: string; type: string }) {
if (draggedId !== id) {
moveCard(draggedId, id)
}
},
})
connectDrag(ref)
connectDrop(ref)
const opacity = isDragging ? 0 : 1
const containerStyle = useMemo(() => ({ ...style, opacity }), [opacity])
return (
<div ref={ref} style={containerStyle} data-handler-id={handlerId}>
{text}
</div>
)
})