Skip to content

Commit

Permalink
fix(searchbar): clear controlled searchbar
Browse files Browse the repository at this point in the history
  • Loading branch information
dextertanyj committed Jul 26, 2023
1 parent e121477 commit 252f520
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
18 changes: 18 additions & 0 deletions react/src/Searchbar/Searchbar.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useState } from 'react'
import { Box, Flex, Stack, Text } from '@chakra-ui/react'
import { Meta, StoryFn } from '@storybook/react'

Expand Down Expand Up @@ -34,6 +35,23 @@ ExpandableOpen.args = {
}
ExpandableOpen.storyName = 'Expandable/Open'

export const Controlled: StoryFn<SearchbarProps> = (args) => {
const [state, setState] = useState<string>('')
return (
<Stack direction="column" align="flex-start">
<Text>External State: {state}</Text>
<Searchbar
{...args}
value={state}
onChange={(e) => setState(e.target.value)}
/>
</Stack>
)
}
Controlled.args = {
defaultIsExpanded: true,
}

export const Sizes: StoryFn<SearchbarProps> = (args) => {
return (
<Stack direction="column" align="flex-start">
Expand Down
9 changes: 8 additions & 1 deletion react/src/Searchbar/Searchbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ export const Searchbar = forwardRef<SearchbarProps, 'input'>(
(
{
onSearch,
onChange,
defaultIsExpanded,
isExpanded: isExpandedProp,
onExpansion: onExpansionProp,
Expand Down Expand Up @@ -103,14 +104,19 @@ export const Searchbar = forwardRef<SearchbarProps, 'input'>(
)

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 = ''
}
if (collapseOnClear) {
onExpansion(false)
}
innerRef.current?.focus()
}, [collapseOnClear, onExpansion])
}, [onChange, collapseOnClear, onExpansion])

const handleExpansion = useCallback(() => {
onExpansion(true)
Expand Down Expand Up @@ -146,6 +152,7 @@ export const Searchbar = forwardRef<SearchbarProps, 'input'>(
ref={inputRef}
sx={styles.field}
onKeyDown={handleSearch}
onChange={onChange}
{...props}
/>
{showClearButton && isExpanded && (
Expand Down

0 comments on commit 252f520

Please sign in to comment.