NextJS, add Auto Suggest component to input field #207313
Replies: 2 comments 1 reply
|
Hi @Fred638 , The pattern is: <div className="autosuggest-container">
<input
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
onFocus={() => setShowSuggestions(true)}
/>
{showSuggestions && (
<AutoSuggestComponent
suggestions={filteredSuggestions}
onSelect={handleSelect}
/>
)}
</div>Key points:
Full example: import { useState } from 'react';
import AutoSuggest from '@/components/AutoSuggest';
export default function SearchInput() {
const [searchTerm, setSearchTerm] = useState('');
const [showSuggestions, setShowSuggestions] = useState(false);
const suggestions = ['Apple', 'Apricot', 'Avocado'].filter(s =>
s.toLowerCase().includes(searchTerm.toLowerCase())
);
return (
<div className="autosuggest-container">
<input
type="text"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
onFocus={() => setShowSuggestions(true)}
onBlur={() => setTimeout(() => setShowSuggestions(false), 100)}
placeholder="Search..."
/>
{showSuggestions && suggestions.length > 0 && (
<AutoSuggest
suggestions={suggestions}
onSelect={(selected) => {
setSearchTerm(selected);
setShowSuggestions(false);
}}
/>
)}
</div>
);
}Notes:
So: they're siblings in the DOM, positioned together with CSS, and connected via state/callbacks in React. That's the standard pattern. |
|
No, the Auto-Suggest dropdown/list component does not need to be physically rendered inside the element. In HTML/DOM structure, an element cannot contain child elements anyway, so they must be sibling elements or separate containers tied together via layout and ARIA attributes. To make an Auto-Suggest component work correctly alongside an input field, follow these best practices:
Position the Auto-Suggest list using position: absolute directly below the input field. Alternatively, render the suggestion list at the document root via a Portal or Floating UI library to prevent issues with overflow: hidden on parent containers.
Set role="combobox" and aria-autocomplete="list" on the . Set aria-expanded="true/false" on the input depending on whether suggestions are visible. Set role="listbox" on the suggestion container and role="option" on each suggestion item. Link them using aria-controls="suggestion-list-id" on the input and update aria-activedescendant as the user navigates through suggestions with arrow keys.
Click Outside: Close the suggestions when a user clicks anywhere outside the input/dropdown container. |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
🏷️ Discussion Type
Question
Body
Hi,
I have created an Auto-Suggest component that works as expected. There are no issues when importing and using the component on the target page. However, I need to add this functionality to an input field. Does the Auto-Suggest need to be inside the input field?
Guidelines
All reactions