Skip to content

Commit

Permalink
Focus button when a value is selected
Browse files Browse the repository at this point in the history
  • Loading branch information
florianduros committed Aug 6, 2024
1 parent 23e3548 commit 9b3318c
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion src/components/Dropdown/Dropdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,15 @@ export const Dropdown = forwardRef<HTMLButtonElement, DropdownProps>(
setState,
);

const buttonRef = useRef<HTMLButtonElement | null>(null);
useEffect(() => {
// Focus the button when the value is set
// Test if the value is undefined to avoid focusing on the first render
if (state.value !== undefined) {
buttonRef.current?.focus();
}
}, [state]);

const hasPlaceholder = state.text === placeholder;
const buttonClasses = classNames({
[styles.placeholder]: hasPlaceholder,
Expand Down Expand Up @@ -135,7 +144,16 @@ export const Dropdown = forwardRef<HTMLButtonElement, DropdownProps>(
aria-labelledby={labelId}
aria-controls={contentId}
aria-expanded={open}
ref={ref}
ref={(element) => {
// Private ref to focus the button
buttonRef.current = element;
// Handle forwarded ref
if (typeof ref === "function") {
ref(element);
} else if (ref) {
ref.current = element;
}
}}
onClick={() => setOpen((_open) => !_open)}
onKeyDown={onComboboxKeyDown}
{...props}
Expand Down

0 comments on commit 9b3318c

Please sign in to comment.