From f7a4a64a265163cfea1679282f2b716bdb79d5e3 Mon Sep 17 00:00:00 2001 From: anlerkan Date: Mon, 13 May 2024 12:07:44 +0300 Subject: [PATCH] fix(list-item): fix event bubbling issue and improve accessibility --- src/list/item/ListItem.tsx | 38 ++++++++++++++++++++++---------------- 1 file changed, 22 insertions(+), 16 deletions(-) diff --git a/src/list/item/ListItem.tsx b/src/list/item/ListItem.tsx index dc9c787b..d4f51f8c 100644 --- a/src/list/item/ListItem.tsx +++ b/src/list/item/ListItem.tsx @@ -30,27 +30,30 @@ function ListItem({ listItemRef }: ListItemProps) { const containerClassName = classNames("list-item", customClassName); - let listItem = ( -
  • - {children} -
  • - ); + const listItemProps: React.DetailedHTMLProps< + React.LiHTMLAttributes, + HTMLLIElement + > & { + "data-testid": string | undefined; + } = { + ref: listItemRef, + id, + "data-testid": testid, + className: containerClassName, + role, + "aria-selected": ariaSelected + }; + let listItem =
  • {children}
  • ; if (clickableListItemProps) { listItem = ( -
  • +
  • + onKeyDown={handleKeyDown}> {children}
  • @@ -60,11 +63,14 @@ function ListItem({ return listItem; function handleClick(event: React.SyntheticEvent) { - clickableListItemProps!.onClick(event); + event.preventDefault(); + event.stopPropagation(); + + clickableListItemProps?.onClick(event); } - function handleKeyPress(event: React.KeyboardEvent) { - if (event.key === KEYBOARD_EVENT_KEY.ENTER) { + function handleKeyDown(event: React.KeyboardEvent) { + if ([KEYBOARD_EVENT_KEY.ENTER, KEYBOARD_EVENT_KEY.SPACE].includes(event.key)) { handleClick(event); } }