0

I have a div that has subscription for both onClick and onKeyPress (Enter click).

the desired behaviour for mouse click is: first click - open popup, second click - close popup.

the desired behaviour for enter click is: open popup.

when tabbing the focus to the div and click enter the subscribed method is fired twice, and it needs to be fired only once. since, the same function is called twice on enter click, it opens and closes the popup.

i tried the followings:

  1. subscribe to keyUp/keyDown instead of onKeyPress.
  2. checking, in the onClick subscription if the event.detail === 0, but it was 0, when enter clicked also.
  3. in onClick, checking if the event.type === 'mousedown', but it was always equal to 'click'
  4. subscribe to onMouseDown/Up instead of onClick, the enter clicked stopped working.

this is the component firing the event

const eventPressHandler = e => {
    if (e.key === 'Enter') {
      return handleEventClick(e, true);
    }

    if (e.key === 'Tab' || (e.shiftKey && e.key === 'Tab')) {
      return closeExpanded();
    }
  }

  return (
    <>
      <div
        onClick={handleEventClick}
        onKeyPress={eventPressHandler}
        className={st(
          classes.root,
          { isAllDay, isInPopper, isMultiDay, isMobile, isAgenda, isCut, isWeekend },
          className
        )}
      >
        {event}
      </div>
      {popper}
    </>
  )
};

this is the handler in the parent component:

const handleEventClick = (eventElement, isKeyClicked) => {
    isKeyClicked && setIsEventEventEntered(true);
    setExpanded(
      expanded || type === EventTypes.ShowMore ?
        null :
        eventElement.currentTarget,
      () => {
        onEventExpanded && onEventExpanded(expandedData) // i use custom hook to fire functions after the setState
      }
    );
  }

I looked in a lot of similar issues but none of them had solution that worked for me.

Itay Tur
  • 683
  • 1
  • 15
  • 40
  • Is it fair to say that the `onClick` should simply toggle the popper state, and the `onKeypress` should just toggle it open, based on the description of the desired behavior? It's a bit unclear what you say the issue is caused by. Is it the tabbing to the div, and then clicking on it instead of keypressing enter on it, that causes something to double invoke? What is being called twice? – Drew Reese Jan 17 '21 at 09:38
  • @DrewReese your first guess was the right one, but i already figure it out, thx anyway :) – Itay Tur Jan 17 '21 at 18:49

1 Answers1

0

i solved it like this:

onClick={e => e.detail === 1 && handleEventClick(e) }
onKeyUp={eventPressHandler}
Itay Tur
  • 683
  • 1
  • 15
  • 40