Skip to content

Commit

Permalink
fix(select): options list width calc
Browse files Browse the repository at this point in the history
  • Loading branch information
reme3d2y committed Apr 9, 2021
1 parent a40ffcf commit 5294af7
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ exports[`Snapshots tests should display opened correctly 2`] = `
class="optionsList"
id="downshift-3-menu"
role="listbox"
style="min-width: 0;"
style="min-width: 0px;"
>
<div
class="optionsList m"
Expand Down
25 changes: 15 additions & 10 deletions packages/select/src/components/base-select/Component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import React, {
KeyboardEvent,
FocusEvent,
useEffect,
useLayoutEffect,
} from 'react';
import mergeRefs from 'react-merge-refs';
import cn from 'classnames';
Expand Down Expand Up @@ -75,6 +76,7 @@ export const BaseSelect = forwardRef(
) => {
const rootRef = useRef<HTMLLabelElement>(null);
const fieldRef = useRef<HTMLInputElement>(null);
const listRef = useRef<HTMLDivElement>(null);

const itemToString = (option: OptionShape) => (option ? option.key : '');

Expand Down Expand Up @@ -187,15 +189,11 @@ export const BaseSelect = forwardRef(
});

const menuProps = (getMenuProps as (options: object, additional: object) => void)(
{},
{ ref: listRef },
{ suppressRefError: true },
);
const inputProps = getInputProps(getDropdownProps({ ref: mergeRefs([ref, fieldRef]) }));

const optionsListMinWidth = rootRef.current
? rootRef.current.getBoundingClientRect().width
: 0;

const handleFieldFocus = (event: FocusEvent<HTMLDivElement | HTMLInputElement>) => {
if (onFocus) onFocus(event);

Expand Down Expand Up @@ -285,6 +283,18 @@ export const BaseSelect = forwardRef(
if (defaultOpen) openMenu();
}, [defaultOpen, openMenu]);

useLayoutEffect(() => {
if (listRef.current) {
const widthAttr = optionsListWidth === 'field' ? 'width' : 'minWidth';

const optionsListMinWidth = rootRef.current
? rootRef.current.getBoundingClientRect().width
: 0;

listRef.current.style[widthAttr] = `${optionsListMinWidth}px`;
}
}, [open, optionsListWidth, options, selectedItems]);

const renderValue = useCallback(
() =>
selectedItems.map(option => (
Expand Down Expand Up @@ -374,11 +384,6 @@ export const BaseSelect = forwardRef(
<div
{...menuProps}
className={cn(optionsListClassName, styles.optionsList)}
style={{
[optionsListWidth === 'field'
? 'width'
: 'minWidth']: optionsListMinWidth,
}}
>
<OptionsList
{...optionsListProps}
Expand Down

0 comments on commit 5294af7

Please sign in to comment.