How to Add Placeholder to Listbox Select Element in Headless UI


How can we add a placeholder to the Listbox element from Headless UI?

Example scenario

Suppose we’re working with an array of users in our state.

const [users, setUsers] = useState([
  { id: 0, name: "dog" },
  { id: 1, name: "cat" },
]);

Each user has an id and a name.

Placeholder text in Listbox

We want to add some placeholder text (i.e. Select user) for when no option is selected.

We can add the ternary operator in the <Listbox.Button> element to achieve this.

import React, { useState } from 'react';
import { Listbox } from '@headlessui/react';

const ListboxComponent = ({ users }) => {
  const [selected, setSelected] = useState();
  return (
    <Listbox value={selected} onChange={setSelected}>
      <Listbox.Button>{selected ? selected.name : "Select user"}</Listbox.Button>
      <Listbox.Options>
        {users.map(user => (
          <Listbox.Option key={user.id} value={user}>
            {user.name}
          </Listbox.Option>
        ))}
      </Listbox.Options>
    </Listbox>
  );
}