How to implement hotkeys to a ShadcnUI dropdown?

40 Views Asked by At

I'm using a dropdown for me to make a couple of options and I decided to put the dropdown content into its own component called <DropdownContentHere />, like this:

Parent

<DropdownMenu>
  <DropdownMenuTrigger asChild>
    <Button className="h-10 font-bold text-white rounded-lg bg-tn-500">
      {selectedOption}
      <ChevronDown className="w-5 h-5 ml-2" />
    </Button>
  </DropdownMenuTrigger>
  <DropdownContentHere />
</DropdownMenu>

<DropdownContentHere />

<DropdownMenuContent className="w-56 p-4 bg-nn-0 rounded-xl">
  <DropdownMenuGroup>
    {options.map((option) => (
      <DropdownMenuCheckboxItem
        key={`view-${view.label}`}
        checked={selectedView === option.label}
        onClick={() => handleChangeOption(option.label, option.path)}
      >
        <span className="font-normal">{option.label}</span>
        <DropdownMenuShortcut>{option.shortcut}</DropdownMenuShortcut>
      </DropdownMenuCheckboxItem>
    ))}
  </DropdownMenuGroup>
</DropdownMenuContent>

And since for each option, I want to implement hotkeys for each of them, I implemented hotkeys as such (inside of the <DropdownContent Here /> component:

const handleKeyPress = useCallback((event) => {
  console.log(`Key pressed: ${event.key}`);
}, []);

useEffect(() => {
  // attach the event listener
  document.addEventListener("keydown", handleKeyPress);

  // remove the event listener
  return () => {
    document.removeEventListener("keydown", handleKeyPress);
  };
}, [handleKeyPress]);

But the issue is that, this keydown event happens even if the dropdown content is active/expanded. Is there a way I can isolate this keydown event so that the hotkeys can only happen when I activate/expand the dropdown component?

0

There are 0 best solutions below