Skip to content

Commit

Permalink
add keyboard navigation support to Listbox
Browse files Browse the repository at this point in the history
  • Loading branch information
therealchrisrock committed Feb 4, 2024
1 parent ae97eec commit a14de4f
Showing 1 changed file with 13 additions and 13 deletions.
@@ -1,7 +1,7 @@
import {useRef, Suspense} from 'react';
import {useRef, Suspense, Fragment} from 'react';
import {Disclosure, Listbox} from '@headlessui/react';
import {defer, redirect, type LoaderFunctionArgs} from '@shopify/remix-oxygen';
import {useLoaderData, Await} from '@remix-run/react';
import {useLoaderData, Await, useNavigate} from '@remix-run/react';
import type {ShopifyAnalyticsProduct} from '@shopify/hydrogen';
import {
AnalyticsPageType,
Expand Down Expand Up @@ -216,7 +216,7 @@ export function ProductForm({
const {product, analytics, storeDomain} = useLoaderData<typeof loader>();

const closeRef = useRef<HTMLButtonElement>(null);

const navigate = useNavigate();
/**
* Likewise, we're defaulting to the first variant for purposes
* of add to cart if there is none returned from the loader.
Expand All @@ -234,7 +234,11 @@ export function ProductForm({
...analytics.products[0],
quantity: 1,
};

const onListboxSelection = (value: string) => {
if (!closeRef?.current) return;
closeRef.current.click();
navigate(value);
};
return (
<div className="grid gap-10">
<div className="grid gap-4">
Expand All @@ -255,7 +259,7 @@ export function ProductForm({
<div className="flex flex-wrap items-baseline gap-4">
{option.values.length > 7 ? (
<div className="relative w-full">
<Listbox>
<Listbox onChange={onListboxSelection}>
{({open}) => (
<>
<Listbox.Button
Expand All @@ -281,27 +285,23 @@ export function ProductForm({
.map(({value, to, isActive}) => (
<Listbox.Option
key={`option-${option.name}-${value}`}
value={value}
value={to}
as={Fragment}
>
{({active}) => (
<Link
to={to}
<li
className={clsx(
'text-primary w-full p-2 transition rounded flex justify-start items-center text-left cursor-pointer',
active && 'bg-primary/10',
)}
onClick={() => {
if (!closeRef?.current) return;
closeRef.current.click();
}}
>
{value}
{isActive && (
<span className="ml-2">
<IconCheck />
</span>
)}
</Link>
</li>
)}
</Listbox.Option>
))}
Expand Down

0 comments on commit a14de4f

Please sign in to comment.