Skip to content

Commit

Permalink
refactor(Autocomplete): Use hook pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
thyhjwb6 committed Apr 27, 2022
1 parent f617637 commit 6d122c1
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { useHighlightedIndex } from './hooks/useHighlightedIndex'
import { useAutocomplete } from './hooks/useAutocomplete'
import { useMenuVisibility } from '../SelectBase/hooks/useMenuVisibility'
import { useExternalId } from '../../hooks/useExternalId'
import { useToggleButton } from './hooks/useToggleButton'

export interface AutocompleteProps extends SelectBaseProps {
/**
Expand All @@ -32,6 +33,7 @@ export const Autocomplete: React.FC<AutocompleteProps> = ({
}) => {
const { hasError, inputRef, items, onInputValueChange, onIsOpenChange } =
useAutocomplete(React.Children.toArray(children), isInvalid)
const { onToggleButtonKeyDownHandler } = useToggleButton(inputRef)
const id = useExternalId('autocomplete', externalId)

const {
Expand Down Expand Up @@ -96,7 +98,11 @@ export const Autocomplete: React.FC<AutocompleteProps> = ({
onClearButtonClick={() => {
reset()
}}
toggleButtonProps={getToggleButtonProps()}
toggleButtonProps={getToggleButtonProps({
onKeyDown: (e: React.KeyboardEvent<HTMLButtonElement>) => {
onToggleButtonKeyDownHandler(e)
},
})}
value={selectedItem ? itemToString(selectedItem) : ''}
{...rest}
>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import React, { useCallback } from 'react'

export function useToggleButton(inputRef: React.RefObject<HTMLInputElement>): {
onToggleButtonKeyDownHandler: (
e: React.KeyboardEvent<HTMLButtonElement>
) => void
} {
const onToggleButtonKeyDownHandler = useCallback(
(e: React.KeyboardEvent<HTMLButtonElement>) => {
if (e.code === 'ArrowDown') {
inputRef.current?.focus()
}
},
[inputRef]
)

return {
onToggleButtonKeyDownHandler,
}
}

0 comments on commit 6d122c1

Please sign in to comment.