J
J
justifycontent2021-07-12 08:14:04
React
justifycontent, 2021-07-12 08:14:04

Why is the event fired 2 times?

When you click on closeBtnRef (the button that closes the window), the handler for this element is called twice, i.e. 'done' is consolidated twice.

import React from 'react'
import scss from './Cart.module.scss'
import ItemCart from '../ItemCart/ItemCart'
import ButtonGreen from '../Button/ButtonGreen'
import ClassNames from 'classnames'
import { useDispatch, useSelector } from 'react-redux'
import setVisibility from '../../redux/actions/cart'

const Cart = () => {
  const overlayRef = React.useRef()
  const closeBtnRef = React.useRef()

  const { visibility } = useSelector(({ cart }) => ({
    visibility: cart.visibility,
  }))

  const closeCart = e => {
    const path = e.nativeEvent.path
    if (e.target === closeBtnRef.current) {
      console.log('done')
    }
  }

  return (
    <div
      className={ClassNames(scss.overlay, {
        [scss.hide]: !visibility
      })}
      ref={overlayRef}
      onClick={closeCart}
    >
      <div className={scss.cart}>
        <h2>Корзина <span ref={closeBtnRef} onClick={closeCart} className={scss.close}/></h2>
        <div className={scss.list}>
          <ItemCart imgUrl='https://i.ibb.co/LYvrTjh/sneakers-12.jpg' name='Мужские Кроссовки Nike Air Max 270' price='12999'/>
        </div>
        <ul className={scss.totalBlock}>
          <li>
            <span>Итого:</span>
            <div />
            <b>21 498 руб.</b>
          </li>
          <li>
            <span>Налог 5%:</span>
            <div />
            <b>1074 руб.</b>
          </li>
        </ul>
        <ButtonGreen next>Оформить заказ</ButtonGreen>
      </div>
    </div>
  )
}

export default Cart

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Artyomov, 2021-07-12
@ArtyomovAnton

Add to the handler
e.stopPropagation();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question