0

So i'm building an app and since i'm using combobox multiple times i decided to create a reusable component as follow ( also is it necessary ? just curious )

import { useState, Fragment } from 'react'
import { Combobox } from '@headlessui/react'

function AppCombobox ({ data, selectedPerson, setSelectedPerson, value, displayValue}) {

return (
   <>
    <Combobox value={selectedPerson} onChange={setSelectedPerson}>
      <Combobox.Input
        as={Fragment}
        onChange={(event) => setQuery(event.target.value)}
        displayValue={(person) => person.name}
      >
        <input />
      </Combobox.Input>
      <Combobox.Options>
        {data.map((person) => (
          <Combobox.Option key={person.id} value={person}>
            {({ active, selected }) => (
            <>
                <span className={cn('block truncate', selected && 'font-semibold')}>{person.name}</span>
                {selected && (
                    <span className={cn('absolute inset-y-0 right-0 flex items-center pr-4', active ? 'text-white' : 'text-indigo-600')}>
                    <CheckIcon className="h-5 w-5" aria-hidden="true"/>
                 </span>
                )}
            </>
        )}
          </Combobox.Option>
        ))}
      </Combobox.Options>
    </Combobox>
   </>
);

Parent Element

export default function Parent () {
 
   const [selectedPerson, setSelectedPerson] = useState(null)

   
   const people = [
      { id: 1, name: 'Durward Reynolds' },
      { id: 2, name: 'Kenton Towne' },
      { id: 3, name: 'Therese Wunsch' },
      { id: 4, name: 'Benedict Kessler'},
      { id: 5, name: 'Katelyn Rohan' },
   ]
   
    return (
       <AppCombobox value={selectedPerson} setSelectedPerson={setSelectedPerson} data={people}/>
    )

}

The problem i'm facing is that When i have the state in the child element ( AppCombobox ) and i select an element, the selected element ui changes and has a checkbox next to it(see attached picture). but when i move the state to the parent element, The combobox checkIcon of the selected element doesn't get rendered. can you please help me out i've spend 2 hours trying to fix this bug

enter image description here

Sb Zakaria
  • 311
  • 6
  • 18

0 Answers0