Skip to main content

AutoComplete

Prerequisite

root css
/* datalist 고유의 picker icon 삭제 */
input::-webkit-calendar-picker-indicator {
opacity: 0;
}

Code

components/Autocomplete/index.tsx
import { useMemo } from 'react'
import type { FC, OptionHTMLAttributes, ComponentProps } from 'react'
import { Input } from 'components'
import { getRandomString } from 'services'

interface Props extends ComponentProps<typeof Input> {
options: Array<OptionHTMLAttributes<HTMLOptionElement>['value']>
id?: string
}

const Autocomplete: FC<Props> = ({ options, ...props }) => {
const id = useMemo(() => getRandomString(), [])
return (
<>
<Input {...props} list={props.id || id} />
<datalist id={props.id || id}>
{options.map((value, key) => (
<option value={value} key={key} />
))}
</datalist>
</>
)
}

export default Autocomplete

Props

NameTypeDefault
options*array of strings
idstring

Example

References

https://developer.mozilla.org/ko/docs/Web/HTML/Element/datalist