Search bar suggestion dropdown

Anyone have any good resources for making a search bar that has a suggestions dropdown like what you see on Google or Youtube? My main issue is with somehow switching focus to the suggestions list, being able to navigate it with the keyboard, and having it populate the search bar when you hit enter.
No description
Solution:
I think that you can keep the focus on the input, and watch for up and down arrow clicks and change some highlighted or selected state for the suggestions list, so something like this: ```jsx function App () { const [selected,setSelected] = useState(0);...
Jump to solution
2 Replies
Solution
latrechetaher
latrechetaher10mo ago
I think that you can keep the focus on the input, and watch for up and down arrow clicks and change some highlighted or selected state for the suggestions list, so something like this:
function App () {
const [selected,setSelected] = useState(0);
const [inpValue, setInpValue] = useState("");
return (
<Suggestions selected={selected} inpValue={inpValue}>
<input value={inpValue}
onChange={(evt)=>{
setInpValue(evt.target.value)
}}
onKeyDown = {evt=>{
// make sure to check for borders of the list
//if key === arrow up
setSelected(selected++);

//if key === arrow down
setSelected(selected--);
}
/>
</Suggestions>
)
}

function Suggestions(selected, inpValue) {
const sugg = [];
// get the suggestions
return (
<Dropdown>
{sugg.map((el, index) => {
return (
<div key={el.id} className={selected === index ? "selected" : ""}>
{el.title}
</div>
);
})}
</Dropdown>
);
}
function App () {
const [selected,setSelected] = useState(0);
const [inpValue, setInpValue] = useState("");
return (
<Suggestions selected={selected} inpValue={inpValue}>
<input value={inpValue}
onChange={(evt)=>{
setInpValue(evt.target.value)
}}
onKeyDown = {evt=>{
// make sure to check for borders of the list
//if key === arrow up
setSelected(selected++);

//if key === arrow down
setSelected(selected--);
}
/>
</Suggestions>
)
}

function Suggestions(selected, inpValue) {
const sugg = [];
// get the suggestions
return (
<Dropdown>
{sugg.map((el, index) => {
return (
<div key={el.id} className={selected === index ? "selected" : ""}>
{el.title}
</div>
);
})}
</Dropdown>
);
}
Davidguy
DavidguyOP10mo ago
that actually makes a lot of sense. I guess I was overthinking it. Thank you!
Want results from more Discord servers?
Add your server