Skip to content

The first item is not selected by default when Command.List content is dynamic #280

Open

Description

@jaxxreal

Issue description

When content of Command.List is dynamic eg rendering result of a search API endpoint results the first item is not always selected by default.

In case I am doing something wrong, please let me know.

Setup

shadcn's Command component, [email protected]

Repro

Repro steps for stackblitz template I drafted up.

Expected:

  1. Type "air" in the input
  2. When results appear, the first item is highlighted
  3. When no results and Add <query> item appears - it's highlighted since it's the first item in the list

Actual:

  1. Type "air" in the input
  2. When results appear, the first item is NOT highlighted
  3. When no results appear and Add <query> item appears - it's NOT highlighted

EDIT: bringing code sample here, just in case

import { Command, CommandInput, CommandItem, CommandList } from './Command';

export default function App() {
  const [items, setItems] = React.useState([]);
  const [isLoading, setIsLoading] = React.useState(false);
  const [q, setQ] = React.useState('');

  const hasSearchResults = items.length > 0;

  React.useEffect(() => {
    if (!q) {
      return;
    }

    setItems([]);
    setIsLoading(true);

    setTimeout(() => {
      setItems(
        dataArray
          .filter((v) => v.includes(q.toLocaleLowerCase()))
          .map((v, idx) => ({
            name: v,
            id: v + idx,
            onSelect: (value: string) => {
              console.log('Selection was made:', value);
            },
          }))
      );
      setIsLoading(false);
    }, 2000);
  }, [q]);

  return (
    <>
      <h1 className="text-3xl font-bold underline">
        First item default selection issue
      </h1>
      <div>
        <Command
          className="rounded-lg border shadow-md"
          shouldFilter={false}
          loop
        >
          <CommandInput placeholder={'Search...'} onValueChange={setQ} />
          <CommandList className="h-fit">
            {isLoading && (
              <CommandItem key={'spinner'} forceMount>
                Searching...
              </CommandItem>
            )}

            {hasSearchResults &&
              items.map((item) => {
                return <RecordCommandItem key={item.id} {...item} />;
              })}

            {!hasSearchResults && !isLoading && q.length > 0 && (
              <CommandItem
                forceMount
                key="create-new-record"
                value={q}
                onMouseDown={(e) => {
                  e.preventDefault();
                  e.stopPropagation();
                }}
                onSelect={(value: string) => {
                  setQ('');
                  console.log('Created!');
                }}
              >
                {`Add "${q}"`}
              </CommandItem>
            )}
          </CommandList>
        </Command>
      </div>
    </>
  );
}

interface RecordCommandItemProps {
  name: string;
  description: string;
  id: string;
  onSelect: (value: string) => void;
}

function RecordCommandItem({
  name,
  description,
  id,
  onSelect,
}: RecordCommandItemProps) {
  return (
    <CommandItem value={id} onSelect={onSelect}>
      <div className="flex flex-row gap-2 text-sm">
        <div className="font-medium">{name}</div>
        <div className="capitalize text-gray-500">{description}</div>
        <span hidden>{id}</span>
      </div>
    </CommandItem>
  );
}

Activity

  1. costaluu commented on Jul 21, 2024

    @costaluu

    Maybe exposing the store object to control the value stored can be a solution, +1 checked this on chrome and firefox

  2. thomaslaberge commented on Jul 23, 2024

    @thomaslaberge

    Same issue for me did you find a solution ?

  3. thomaslaberge commented on Aug 5, 2024

    @thomaslaberge

    Found a workaround, you can add a Key to the CommandList. When the key changes, the component is fully rerendered.

    For me i added the query as the key. Everytime the query changes, the command is fully rerendered with the right selected first item.

  4. jaxxreal commented on Aug 6, 2024

    @jaxxreal
    Author

    Found a workaround, you can add a Key to the CommandList. When the key changes, the component is fully rerendered.

    For me i added the query as the key. Everytime the query changes, the command is fully rerendered with the right selected first item.

    Hello! I just applied changes to the example I've attached but I see no changes in behavior. Am I doing something wrong?

  5. thomaslaberge commented on Aug 6, 2024

    @thomaslaberge

    For your case II add to put the key at the command level :
    <Command
    className="rounded-lg border shadow-md"
    shouldFilter={false}
    loop
    key={isLoading.toString().concat(q)}
    >

    the general idea is that id a key element is changed, the element will be fuly rerender after a state change. In my case the results list are in a children component. Rerendering this component was enought for my use case. You need to also include the isloading with Q because you want a full rerender when is transition from loading to not loading. This is a woraround, not a best practice

  6. stuartmemo commented on Sep 1, 2024

    @stuartmemo

    If it helps, I had to add autoFocus to the <CommandInput> to stop input losing focus on re-render.

  7. senadir commented on Oct 24, 2024

    @senadir

    Adding a key does kinda mess up the performance and behavior of the list, especially when switching from no results to exists results.

    Adding the key to Command.List is slightly more stable but not as good.

  8. loggerhead commented on Oct 26, 2024

    @loggerhead

    Any solution? Still encountering the problem.

  9. xixixao commented on Nov 21, 2024

    @xixixao

    I suspect others like me are trying to use this component to build a nice "typeahead" kind of experience, and this bug totally breaks it :(

  10. xixixao commented on Nov 22, 2024

    @xixixao

    The problem is that the component is used uncontrolled. To fix this, control the Command instance like this:

      const items = ... // result of async loading
      const [activeItem, setActiveItem] = useState<string | undefined>();
    
      // this is just a classic direct rerender, you could avoid it if you can call
      // setActiveItem from where you load items
      const lastItems = useRef(items);
      if (items !== lastItems.current) {
        lastItems.current = items;
        setActiveItem(items?.[0]?.id ?? undefined);
      }
      
      return (
        <Command
          shouldFilter={false}
          value={activeItem}
          onValueChange={(itemId) => {
            setActiveItem(itemId);
          }}
        >
           ....
               <CommandItem
                key={item.id}
                value={item.id}
  11. jrnxf commented on Dec 1, 2024

    @jrnxf

    The problem is that the component is used uncontrolled. To fix this, control the Command instance like this:

      const items = ... // result of async loading
      const [activeItem, setActiveItem] = useState<string | undefined>();
    
      // this is just a classic direct rerender, you could avoid it if you can call
      // setActiveItem from where you load items
      const lastItems = useRef(items);
      if (items !== lastItems.current) {
        lastItems.current = items;
        setActiveItem(items?.[0]?.id ?? undefined);
      }
      
      return (
        <Command
          shouldFilter={false}
          value={activeItem}
          onValueChange={(itemId) => {
            setActiveItem(itemId);
          }}
        >
           ....
               <CommandItem
                key={item.id}
                value={item.id}

    you shouldn't call setState in the body of the function like this

  12. getinnocuous commented on Feb 24, 2025

    @getinnocuous

    Also having this issue. Has anyone found a workaround?

  13. saevarb commented on Mar 23, 2025

    @saevarb

    I've just encountered this issue. I've also tried to use the Loading item described in the docs, but that has no effect.

    Are there any plans on fixing this, or could you @pacocoursey perhaps point to the code that is responsible for this so I can take a crack at a fix?

  14. widavies commented on Mar 28, 2025

    @widavies

    Same problem here

  15. saevarb commented on Mar 28, 2025

    @saevarb

    I've found a workaround which is just maintaining the selection state yourself on Command, and when data changes, you just set it to the first element in the list.

  16. sirajtahra commented on Apr 14, 2025

    @sirajtahra

    +1

  17. jrnxf commented on Apr 18, 2025

    @jrnxf

    I fixed this in #354 if you guys would like to test it out + upvote for visibility!

  18. Mattciao96 commented on Apr 22, 2025

    @Mattciao96

    Thanks @jrnxf that works perfectly for me!

  19. jaxxreal commented on Oct 6, 2025

    @jaxxreal
    Author

    Hi everyone — I found a neat workaround that doesn’t involve any hacking. I’ll just leave a comment noting that it’s a workaround.

    My app is way more complex — we add a bunch of custom controls on top of the search results — but the overall idea should be clear now.

    https://stackblitz.com/edit/cmdk-first-item-highlight-bug-workaround?file=src%2FApp.tsx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions