Skip to content

Commit

Permalink
feat(Select example): make items accessible with keyboard
Browse files Browse the repository at this point in the history
  • Loading branch information
adamviktora committed Oct 22, 2024
1 parent d973296 commit 710ab0a
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions packages/react-core/src/components/Select/examples/SelectBasic.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ export const SelectBasic: React.FunctionComponent = () => {
const [selected, setSelected] = React.useState<string>('Select a value');
const [isDisabled, setIsDisabled] = React.useState<boolean>(false);

const menuRef = React.useRef<HTMLDivElement>();

const onToggleClick = () => {
setIsOpen(!isOpen);
};
Expand All @@ -18,6 +20,24 @@ export const SelectBasic: React.FunctionComponent = () => {
setIsOpen(false);
};

const onKeyDown = (event: React.KeyboardEvent<HTMLButtonElement | HTMLDivElement>) => {
if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') {
return;
}
event.preventDefault();
setIsOpen(true);

const firstItemSelector = 'li button:not(:disabled),li input:not(:disabled)';
const lastItemSelector = 'li:last-child button:not(:disabled),li:last-child input:not(:disabled)';

setTimeout(() => {
const elementToFocus = menuRef?.current?.querySelector(
event.key === 'ArrowDown' ? firstItemSelector : lastItemSelector
);
elementToFocus && (elementToFocus as HTMLElement).focus();
}, 10);
};

const toggle = (toggleRef: React.Ref<MenuToggleElement>) => (
<MenuToggle
ref={toggleRef}
Expand All @@ -29,6 +49,7 @@ export const SelectBasic: React.FunctionComponent = () => {
width: '200px'
} as React.CSSProperties
}
onKeyDown={onKeyDown}
>
{selected}
</MenuToggle>
Expand All @@ -44,6 +65,7 @@ export const SelectBasic: React.FunctionComponent = () => {
style={{ marginBottom: 20 }}
/>
<Select
ref={menuRef}
id="single-select"
isOpen={isOpen}
selected={selected}
Expand Down

0 comments on commit 710ab0a

Please sign in to comment.