The functionality of ShadCN UI combobox is limited to keyboard inputs and does not respond to mouse

I've built a simple app with just a combobox and a card, designed to be embedded on a Wordpress site using NextJS and ShadCN ui components.

However, I'm facing an issue where the combobox only responds to keyboard input and not mouse clicks. Even when copying examples directly from the ShadCN ui website, it still doesn't work as expected.

I believe it's a minor problem that I'm overlooking, but I can't seem to pinpoint the exact cause.

Here is the code snippet:

'use client'

import { ChevronsUpDown } from 'lucide-react'
import { Batch, batches } from '@/lib/batch'
import { Button } from '@/components/ui/button'
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from '@/components/ui/command'
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover'
import { useState } from 'react'
import InfoCard from './info-card'

// Combobox component definition

export function Combobox() {
  // State variables
  const [open, setOpen] = useState(false)
  const [value, setValue] = useState('')
  const [inputValue, setInputValue] = useState('')
  const [currentItem, setCurrentItem] = useState<Batch | null>(null)

  // Filter batches based on input value
  const filteredBatches = batches.filter((batch) =>
    batch.number.includes(inputValue)
  )

  // Handle click event on batch item
  const handleClick = (batch: Batch) => {
    console.log('clicked')
    setCurrentItem(batch)
    setOpen(false)
  }

  // Render JSX
  return (
    <>
      <Popover open={open} onOpenChange={setOpen}>
        <PopoverTrigger asChild>
          <Button
            variant='outline'
            role='combobox'
            aria-expanded={open}
            className='w-[500px] justify-between'
          >
            {value
              ? batches.find((batch) => batch.number === value)?.number
              : 'Type your batch number...'}
            <ChevronsUpDown className='ml-2 h-4 w-4 shrink-0 opacity-50' />
          </Button>
        </PopoverTrigger>
        <PopoverContent className='w-[500px] p-0'>
          <Command>
            <CommandInput
              placeholder='Search batch number...'
              value={inputValue}
              onValueChange={setInputValue}
            />
            <CommandEmpty>No batch found.</CommandEmpty>
            <CommandList>
              <CommandGroup>
                {filteredBatches.map((batch) => (
                  <CommandItem
                    key={batch.number}
                    value={batch.number}
                    onSelect={() => handleClick(batch)}
                    className='hover:cursor-pointer hover:bg-slate-400'
                  >
                    {batch.number} - {batch.fishery}
                  </CommandItem>
                ))}
              </CommandGroup>
            </CommandList>
          </Command>
        </PopoverContent>
      </Popover>

      <InfoCard batch={currentItem} />
    </>
  )
}

export default Combobox

You can view the deployed version to see that it works with keyboard here:

Find the code here: https://github.com/santivdt/ais-batch-numbers

Hopefully someone has a solution to this issue.

Answer №1

The utility class applied to your element is

data-[disabled]:pointer-events-none
. This class is triggered when the element has the attribute data-disabled present.

By default, the element has the value of data-disabled, even though it is set to false. The presence of the attribute itself is enough for the class to take effect.

If you want the class to apply only when the data-disabled value is true, modify the utility class to:

data-[disabled=true]:pointer-events-none
.

Answer №3

By including

data-[disabled]:pointer-events-auto
in the CommandItem's className, I was able to resolve the issue.

Upon reviewing the command.tsx file, I noticed that it already contained data-[disabled=true] rather than data-[disabled] as suggested in previous responses.

Answer №4

The issue I am facing persists despite my efforts to solve it. Upon inspection, I discovered that the

data-[disabled=true]:pointer-events-none
property is set in the CommandItem, requiring the use of a keyboard to select an item. To resolve this, I included
className="pointer-events-auto"
in the CommandItem.

<CommandItem value={proj.label}
  key={proj.value}
  onSelect={() => {form.setValue("projects", proj.value)}}
  className="pointer-events-auto"> // Include this line
  {proj.label}
  <Check className={cn("ml-auto h-4 w-4", proj.value === field.value ? "opacity-100": "opacity-0")}/>
</CommandItem>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for incorporating asynchronous page components as a child element in next.js?

Utilizing the latest functionality in next.js for server-side rendering, I am converting my component to be async as per the documentation. Here is a simple example of my page component: export default async function Home() { const res = await fetch( ...

Pass the object either in JSON format or as a variable using the drag and drop feature

Here's a quick question: when using the Drag and Drop system, I'm not sure which method is better. Is it more efficient to : utilize setData and getData to transfer a JavaScript object? (Utilizing JSON conversion since setData only passes st ...

Having trouble setting up my Next.js application on Docker platform

I am currently working with a VPS running Ubuntu 22.04 and my goal is to create and run a Next.js application within a Docker container. Instead of having NodeJS installed directly on Ubuntu, I want the node:18-alpine image to handle all the necessary fun ...

Improving the style of Google Maps InfoWindows for right-to-left languages

I'm currently working on a Google Maps marker infowindow and trying to adjust the padding specifically for RTL languages. Here's what I've attempted so far: google.maps.event.addListener(marker, 'click', function () { i ...

Switching measurement unit to jQuery when retrieving image weight

After coming across a solution on this question, I am looking to determine the weight of an image from a file input. The solution I found displays the result in MiB (Mebibyte) unit. Is there a way to show the image weight using the same code, but in a diff ...

Highlighting text within ReactJS using Rasa NLU entities

Currently, I am working on a React application that retrieves data from the Rasa HTTP API and displays it. My goal is to tag the entities in a sentence. The code functions correctly for single-word entities but encounters issues with two-word entities (onl ...

What is the best way for ensuring that the test only proceeds after useEffect's update function has been executed?

function CustomApp() { let [counter, setCounter] = useState(0); useEffect(() => { setCounter(1); }, []); //<-------------------------set a checkpoint here to debug, triggered only once return counter; } // trouble-shooting ...

Include a function call within a ternary operator in JSX code

I am looking to call a function within a ternary operator condition. Here is what my code looks like: {snapshot.Bid[0].Price !== 'undefined' ? `(${initialOrderInfo.snapshot.Bid[0].Price}` {renderCurrencySymb ...

What is the reason for the error message "ReferenceError: categories is not defined" appearing in my AngularJS code?

I don't understand why I am encountering this error and cannot access the data from the Json file, even though $scope.categories is already defined. Can someone help me with this issue? Below is my controller code: (function(){ app.controller(&a ...

Is there a way to update and reload the latest data in ApexCharts?

Can anyone assist me in resolving my issue? I have an ApexCharts that displays data, and I need it to refresh whenever the user desires. The data should also be updated with the latest information. However, I am unsure how to reload the data in ApexCharts. ...

Incorporating sliding animation into Angular's ng-repeat directive

I am currently working on my code to create multiple divs with a hide button in each one. When the hide button is clicked, I want the corresponding div to fade away and the divs below it to smoothly move up to fill the space left behind. Below is the snip ...

What is the best way to eliminate the time component from an object in JavaScript?

I have a task to strip the time information from a specific property in my object. To achieve this, I am checking if any timestamps are present in the property value by using an index. Here is the initial input: input [ { "S": "Charge Interest Agai ...

Troublesome Outcome: Next.js Forms Function Smoothly in Local Environment but Encounter Issues when Deploy

I am facing a puzzling issue with my Next.js application. Despite successfully using Nodemailer locally to submit forms, I keep encountering an "Internal Server Error" when deploying to cPanel. I have tried different solutions, but the problem persists. As ...

Issue with ESlint global installation in macOS root terminal

Having trouble installing ESlint globally on my Mac running Mojave 10.14.6. Every time I try to run 'npm install -g eslint' I keep encountering this error: Your operating system has rejected the operation. npm ERR! It seems that you lack the nec ...

sending a pair of variables via jQuery and AJAX

Having difficulty posting two variables using ajax and jquery when a button on a confirm window is pressed. Each variable can be displayed separately, but not both at the same time. UPDATE - Issue resolved. I overlooked including a necessary file. My mist ...

Passing a selected option in a select box to another website is achievable using JavaScript

I'm still learning JavaScript and I would like to have a user be directed to another page when they select an option from a dropdown menu. Any suggestions on how to accomplish this? ...

Should Google Analytics be integrated directly or through the use of Tag Manager?

Currently in the process of developing a substantial NextJS application, I have come across the need to incorporate Google Analytics 4 for the client. Wondering whether it would be more effective to integrate Google Analytics directly into my application o ...

Error message thrown on the login page: "Attempting to access property 'push' of an undefined object"

I'm currently working on a login page using JWT and I'm facing an issue with trying to redirect the user to the home page after successful login. I am using this.props.history.push("/") for redirection but I keep getting an error: TypeError: Cann ...

What is the best way to save a table to local storage in HTML after dynamically adding rows using JavaScript or AngularJS?

I came across this code on the following link. http://codepen.io/akashmitra/pen/eNRVKo HTML <div ng-app="app" ng-controller="Ctrl"> <table class="table table-bordered table-hover table-condensed"> <tr style="font-weight: bold"> ...

Ways to smoothly navigate to a specific element across various browsers with jQuery animation

This particular piece of code is causing some cross-browser compatibility issues: jQuery('body').animate({scrollTop: target.offset().top}, 300); Interestingly, it works perfectly in Firefox but not in Chrome. A different version of the same co ...