cssreactjstailwind-css

React HeadlessUI + Custom Radio Dropdown with “Select All”


I'm building a React component that mimics a custom dropdown using Headless UI's Listbox, with radio buttons inside the dropdown. It supports a "Select All" option that should populate the payload with all options' codes.

enter image description here

enter image description here


Solution

  • Your component is almost correct, but there are two main issues in how you're handling the radio buttons.
    Changes made:

    Replace your current <li> inside Listbox.Option with this:

    <li
      className={`relative cursor-pointer select-none py-2 pl-10 pr-4 text-sm ${
        active ? 'bg-purple-100 text-purple-900' : 'text-gray-900'
      }`}
    >
      <span className="absolute inset-y-0 left-3 flex items-center">
        <input
          type="radio"
          checked={
            option.code === '__ALL__'
              ? isAllSelected
              : selectedCode === option.code
          }
          readOnly
          className="h-4 w-4 text-purple-600 pointer-events-none"
        />
      </span>
      <span
        className={`block truncate ${
          option.code === '__ALL__'
            ? isAllSelected
            : selectedCode === option.code
            ? 'font-medium'
            : 'font-normal'
        }`}
      >
        {option.name}
      </span>
    </li>