burger-online

Форк
0
/
ingredient-constructor.tsx 
64 строки · 2.0 Кб
1
import {ConstructorElement, DragIcon} from '@ya.praktikum/react-developer-burger-ui-components'
2
import React from 'react'
3
import {useDrag, useDrop} from 'react-dnd'
4
import {useAppDispatch} from '../../hooks'
5
import {removeIngredient, sortedIngredients} from '../../redux/constructor/slice'
6
import {TIngredient} from '../../types'
7
import styles from './ingredient-constructor.module.css'
8
import {TIngredientConstructor} from './types'
9

10
const IngredientConstructor: React.FC<TIngredientConstructor> = ({type, ingredient, index}) => {
11
  const dispatch = useAppDispatch()
12
  const ref = React.useRef<HTMLLIElement>(null)
13

14
  const onClickRemoveIngredient = (item: TIngredient) => {
15
    dispatch(removeIngredient(item))
16
  }
17

18
  const [, drag] = useDrag({
19
    type: 'burger',
20
    item: {index},
21
  })
22

23
  const [{isDrop}, drop] = useDrop({
24
    accept: 'burger',
25
    collect: monitor => ({
26
      isDrop: monitor.isOver(),
27
    }),
28
    hover: (item: {index: number}) => {
29
      if (!ref.current) return
30
      const dragIndex = item.index
31
      const hoverIndex = index as number
32

33
      if (dragIndex === hoverIndex) return
34
      dispatch(sortedIngredients({dragIndex, hoverIndex}))
35

36
      item.index = hoverIndex
37
    },
38
  })
39

40
  !ingredient.isLocked && drag(drop(ref))
41

42
  const isClasses = `${ingredient.isLocked ? styles.bun : styles.other} ${
43
    !ingredient.isLocked && isDrop ? styles.indicator : ''
44
  }`
45

46
  const typeTextBun = type === 'top' ? '(верх)' : type === 'bottom' ? '(низ)' : ''
47

48
  if (!ingredient.name) return null
49
  return (
50
    <li ref={ref} className={isClasses} draggable={ingredient.isLocked ? false : true}>
51
      {!ingredient.isLocked && <DragIcon type='secondary' />}
52
      <ConstructorElement
53
        type={type}
54
        isLocked={ingredient.isLocked}
55
        text={`${ingredient.name} ${typeTextBun}`}
56
        price={ingredient.price}
57
        thumbnail={ingredient.image}
58
        handleClose={() => onClickRemoveIngredient(ingredient)}
59
      />
60
    </li>
61
  )
62
}
63

64
export default IngredientConstructor
65

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.