From 252f5205997bb9a361eacce87fee6514e5773ffb Mon Sep 17 00:00:00 2001 From: Dexter Tan Date: Wed, 26 Jul 2023 14:09:36 +0000 Subject: [PATCH] fix(searchbar): clear controlled searchbar --- react/src/Searchbar/Searchbar.stories.tsx | 18 ++++++++++++++++++ react/src/Searchbar/Searchbar.tsx | 9 ++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/react/src/Searchbar/Searchbar.stories.tsx b/react/src/Searchbar/Searchbar.stories.tsx index dc5968be..6b9247a6 100644 --- a/react/src/Searchbar/Searchbar.stories.tsx +++ b/react/src/Searchbar/Searchbar.stories.tsx @@ -1,3 +1,4 @@ +import { useState } from 'react' import { Box, Flex, Stack, Text } from '@chakra-ui/react' import { Meta, StoryFn } from '@storybook/react' @@ -34,6 +35,23 @@ ExpandableOpen.args = { } ExpandableOpen.storyName = 'Expandable/Open' +export const Controlled: StoryFn = (args) => { + const [state, setState] = useState('') + return ( + + External State: {state} + setState(e.target.value)} + /> + + ) +} +Controlled.args = { + defaultIsExpanded: true, +} + export const Sizes: StoryFn = (args) => { return ( diff --git a/react/src/Searchbar/Searchbar.tsx b/react/src/Searchbar/Searchbar.tsx index d3ec7b5b..f048133f 100644 --- a/react/src/Searchbar/Searchbar.tsx +++ b/react/src/Searchbar/Searchbar.tsx @@ -67,6 +67,7 @@ export const Searchbar = forwardRef( ( { onSearch, + onChange, defaultIsExpanded, isExpanded: isExpandedProp, onExpansion: onExpansionProp, @@ -103,6 +104,11 @@ export const Searchbar = forwardRef( ) const handleClearButtonClick = useCallback(() => { + if (onChange) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + onChange({ target: { value: '' } }) + } if (innerRef.current) { innerRef.current.value = '' } @@ -110,7 +116,7 @@ export const Searchbar = forwardRef( onExpansion(false) } innerRef.current?.focus() - }, [collapseOnClear, onExpansion]) + }, [onChange, collapseOnClear, onExpansion]) const handleExpansion = useCallback(() => { onExpansion(true) @@ -146,6 +152,7 @@ export const Searchbar = forwardRef( ref={inputRef} sx={styles.field} onKeyDown={handleSearch} + onChange={onChange} {...props} /> {showClearButton && isExpanded && (