Theo's Typesafe CultTTC
Theo's Typesafe Cult2y ago
4 replies
Davidguy

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.
image.png
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:

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>
  );
}
Was this page helpful?