From 4c1cf7f61f0118b3a77ce9feea446bf872002ae3 Mon Sep 17 00:00:00 2001 From: Sebastian Florek Date: Fri, 29 Mar 2024 14:20:03 +0100 Subject: [PATCH] feat: add conditional onClick action to chip list (#579) --- src/components/ChipList.tsx | 33 +++++++++++++++++++-------- src/stories/ChipList.stories.tsx | 38 ++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 9 deletions(-) diff --git a/src/components/ChipList.tsx b/src/components/ChipList.tsx index ed0d5822..e4e8defc 100644 --- a/src/components/ChipList.tsx +++ b/src/components/ChipList.tsx @@ -1,6 +1,11 @@ import { Flex, Span } from 'honorable' import isEmpty from 'lodash-es/isEmpty' -import { type ComponentProps, type ReactElement, useState } from 'react' +import { + type ComponentProps, + type Dispatch, + type ReactElement, + useState, +} from 'react' import { HamburgerMenuCollapseIcon } from '../icons' @@ -15,6 +20,8 @@ export type ChipListProps = { transformValue?: TransformFn limit: number emptyState?: JSX.Element | null + onClickCondition?: (value: TValue) => boolean + onClick?: Dispatch } & ChipProps function ChipList({ @@ -22,6 +29,8 @@ function ChipList({ transformValue, limit = 4, emptyState, + onClickCondition, + onClick, ...props }: ChipListProps): ReactElement { const [collapsed, setCollapsed] = useState(true) @@ -37,14 +46,20 @@ function ChipList({ ) : ( There is nothing to display here. ))} - {values.slice(0, collapsed ? limit : undefined).map((v, i) => ( - - {transformValue ? transformValue(v) : `${v}`} - - ))} + {values.slice(0, collapsed ? limit : undefined).map((v, i) => { + const clickable = onClickCondition?.(v) ?? false + + return ( + clickable && onClick(v)} + {...props} + > + {transformValue ? transformValue(v) : `${v}`} + + ) + })} {values.length > limit && ( <> {collapsed && ( diff --git a/src/stories/ChipList.stories.tsx b/src/stories/ChipList.stories.tsx index e55a08e1..a2c65060 100644 --- a/src/stories/ChipList.stories.tsx +++ b/src/stories/ChipList.stories.tsx @@ -68,6 +68,35 @@ function TextTemplate({ onFillLevel, ...args }: any) { ) } +function CustomClickTemplate({ onFillLevel, ...args }: any) { + const VALUES = [ + 'avengers', + 'iron man', + 'doctor strange', + 'thor', + 'black panther', + 'guardians of the galaxy', + ] + + return ( + 0} + wrapper={ + + } + > + + + ) +} + interface Label { key?: string value: string @@ -142,3 +171,12 @@ Empty.args = { size: 'small', onFillLevel: 0, } + +export const CustomClick = CustomClickTemplate.bind({}) +CustomClick.args = { + severity: 'info', + size: 'small', + onFillLevel: 0, + onClickCondition: (value: string) => value === 'avengers', + onClick: (value: string) => alert(value), +}