← Components/Inputs & Forms

AutocompleteInput

autocompleteinput-1779354200570.tsx
'use client';

import { useState, useEffect } from 'react';

interface Suggestion {
  id: number;
  label: string;
}

const suggestions: Suggestion[] = [
  { id: 1, label: 'Apple' },
  { id: 2, label: 'Banana' },
  { id: 3, label: 'Cherry' },
  { id: 4, label: 'Date' },
  { id: 5, label: 'Elderberry' },
];

const AutocompleteInput = () => {
  const [inputValue, setInputValue] = useState('');
  const [filteredSuggestions, setFilteredSuggestions] = useState<Suggestion[]>([]);
  const [activeSuggestionIndex, setActiveSuggestionIndex] = useState(0);

  useEffect(() => {
    const filtered = suggestions.filter((suggestion) =>
      suggestion.label.toLowerCase().includes(inputValue.toLowerCase())
    );
    setFilteredSuggestions(filtered);
    setActiveSuggestionIndex(0);
  }, [inputValue]);

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInputValue(e.target.value);
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'ArrowDown') {
      setActiveSuggestionIndex((prevIndex) =>
        prevIndex < filteredSuggestions.length - 1 ? prevIndex + 1 : prevIndex
      );
    } else if (e.key === 'ArrowUp') {
      setActiveSuggestionIndex((prevIndex) =>
        prevIndex > 0 ? prevIndex - 1 : prevIndex
      );
    } else if (e.key === 'Enter') {
      if (filteredSuggestions.length > 0) {
        setInputValue(filteredSuggestions[activeSuggestionIndex].label);
        setFilteredSuggestions([]);
      }
    }
  };

  const handleSuggestionClick = (suggestion: Suggestion) => {
    setInputValue(suggestion.label);
    setFilteredSuggestions([]);
  };

  return (
    <div className="relative w-full">
      <input
        type="text"
        value={inputValue}
        onChange={handleInputChange}
        onKeyDown={handleKeyDown}
        className="w-full py-2 pl-10 text-sm text-gold border border-zinc-700 rounded-lg bg-zinc-950 focus:outline-none focus:ring-2 focus:ring-gold"
        placeholder="Search..."
      />
      {filteredSuggestions.length > 0 && (
        <ul className="absolute z-10 w-full mt-1 bg-zinc-950 rounded-lg py-2">
          {filteredSuggestions.map((suggestion, index) => (
            <li
              key={suggestion.id}
              className={`py-2 pl-10 pr-4 text-sm cursor-pointer ${
                index === activeSuggestionIndex
                  ? 'bg-zinc-800 text-gold'
                  : 'text-zinc-400 hover:bg-zinc-800 hover:text-gold'
              }`}
              onClick={() => handleSuggestionClick(suggestion)}
            >
              {suggestion.label.replace(
                new RegExp(inputValue, 'gi'),
                (match) => `<span className="text-gold">${match}</span>`
              )}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
};

export default AutocompleteInput;

Component info

CategoryInputs & Forms
Frameworkreact
TierFREE
Views0
Copies0

About

Search input with dropdown suggestions

More from Inputs & Forms

'use client';

import React, { useState } from 'react';

interface RangeSliderProps {
  min: number;
  max: number;
  defaultValue: [number, number];
}

const RangeSlider: React.FC<RangeSliderProps> = ({ min, max, defaultValue }) => {
  const [minVal
RangeSlider
Inputs & Forms
'use client';

import React, { useState } from 'react';

interface Color {
  hex: string;
}

interface Swatch {
  hex: string;
}

const ColorPicker = () => {
  const [color, setColor] = useState<Color>({ hex: '#C9A84C' });
  const [customColor, setCu
ColorPicker
Inputs & Forms
'use client';

import { useState, useEffect } from 'react';

interface Tag {
  id: number;
  name: string;
}

const TagInput = () => {
  const [tags, setTags] = useState<Tag[]>([]);
  const [inputValue, setInputValue] = useState('');
  const [suggest
TagInput
Inputs & Forms
'use client';

import React, { useState } from 'react';

interface File {
  name: string;
  size: number;
  progress: number;
}

const FileUpload = () => {
  const [dragOver, setDragOver] = useState(false);
  const [files, setFiles] = useState<File[]
FileUpload
Inputs & Forms