diff --git a/packages/actify/src/components/Autocomplete/Autocomplete.tsx b/packages/actify/src/components/Autocomplete/Autocomplete.tsx index a97da43..cf46c04 100644 --- a/packages/actify/src/components/Autocomplete/Autocomplete.tsx +++ b/packages/actify/src/components/Autocomplete/Autocomplete.tsx @@ -6,6 +6,8 @@ import { ListBox } from '../ListBox' import { Popover } from '../Popover' import React from 'react' import { TextField } from '../TextFields' +import styles from './autocomplete.module.css' +import { useResizeObserver } from './../../hooks' interface AutocompleteProps extends Omit, 'children'>, @@ -19,10 +21,13 @@ const Autocomplete = (props: AutocompleteProps) => { const state = useComboBoxState({ ...props, defaultFilter: contains }) // Setup refs and get props for child elements. + const ref = React.useRef(null) const inputRef = React.useRef(null) const listBoxRef = React.useRef(null) const popoverRef = React.useRef(null) + const referenceWidth = useResizeObserver(ref as React.RefObject) + const { inputProps, listBoxProps } = useComboBox( { ...props, @@ -34,11 +39,11 @@ const Autocomplete = (props: AutocompleteProps) => { ) return ( -
+
state.setOpen(true)} trailingIcon={ @@ -60,11 +65,11 @@ const Autocomplete = (props: AutocompleteProps) => { {state.isOpen && ( extends AriaSelectOptions, SelectStateOptions { className?: string @@ -21,9 +22,6 @@ interface SelectProps extends AriaSelectOptions, SelectStateOptions { const Select = (props: SelectProps) => { const state = useSelectState(props) - const [referenceWidth, setReferenceWidth] = React.useState< - number | undefined - >(0) const ref = React.useRef(null) const { triggerProps, valueProps, menuProps } = useSelect(props, state, ref) @@ -38,16 +36,7 @@ const Select = (props: SelectProps) => { Tag = OutlinedField } - React.useEffect(() => { - const resizeObserver = new ResizeObserver(() => { - const width = ref?.current?.getBoundingClientRect().width - setReferenceWidth(width) - }) - resizeObserver.observe(ref?.current as Element) - return () => { - resizeObserver.disconnect() - } - }, []) + const referenceWidth = useResizeObserver(ref as React.RefObject) return (
) => { + const [width, setWidth] = React.useState(0) + React.useEffect(() => { + const resizeObserver = new ResizeObserver(() => { + const width = ref?.current?.getBoundingClientRect().width + setWidth(width) + }) + resizeObserver.observe(ref?.current as Element) + return () => { + resizeObserver.disconnect() + } + }, []) + return width +} + +export { useResizeObserver }