latrechetaher
latrechetaher
TTCTheo's Typesafe Cult
Created by Davidguy on 3/18/2024 in #questions
Search bar suggestion dropdown
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>
);
}
5 replies