pacocoursey / cmdk

Fast, unstyled command menu React component.
https://cmdk.paco.me
MIT License
9.56k stars 274 forks source link

Expose getters / setters for selected index? #46

Open agamrp opened 2 years ago

agamrp commented 2 years ago

I wanted to be able to control the selected index from outside the component if possible. Motivation is dealing with sub pages and parent pages. If I go into a sub page and then back out hitting Escape, I wanted the parent page Item to have focus in the List.

Looks like internally there are a couple of helper methods like updateSelectedByChange and updateSelectedToIndex that I wanted to get access to or be able to pass a prop to the Command component indicating initial Item to be selected/focused.

Thanks for putting this library out, seems to be working well for me so far!

pomdtr commented 2 years ago

I found a way to achieve this but it is kind of hacky:

export function CommandWithChild({ goBack }: { goBack?: () => void }) {
  const [child, setChild] = useState<JSX.Element>();

  return (
    child || (
      <Command.List
        onKeyDown={(e) => {
          if (e.key == "Escape" && typeof goBack !== "undefined") {
            goBack()
          }
        }}
      >
        <Command.Item
          onSelect={() =>
            setChild(<ListCommand goBack={() => setChild(undefined)} />)
          }
        />
      </Command.List>
    )
  );
}

Basically when you go in a subpage, you rerender a whole new list instead of trying to tune the existing one.

pacocoursey commented 2 years ago

Good use-case, might expose them under a new hook like const actions = useCmdk().