Search Bar with Two options as dropdown (ReactJS)

Viewed 1085

Let's say I wanted to create a search bar (something similar to Github's search bar) as following specifications in ReactJS:

In an input when user start typing, 2 options as dropdown will appear. And when user click on the option will do something relevant to it.

I found "autocomplete" from Material-UI and tried different sites on Google but I couldn't find the answer I was looking for, those articles I found were all about dropdown menu with defined values.

Any idea or reference? Thank you very much!

search bar sample

1 Answers

You'll need 1 state to hold the input value. Then based on it to render the dropdown below. And you will need a submit handler with an optional search type param to reuse for onClick event of each Option inside the dropdown.

const [keyword, setKeyword] = React.useState('')

const handleSearch = (searchType) => {
  if (searchType) {
    // search with type (Author or Book)
    doSearch({ keyword, type })
  } else {
    // search with keyword only
    doSearch({ keyword })
  }
}

For render:

<input value={keyword} onChange={e => setKeyword(e.target.value)} />
<button onClick={() => handleSearch()}>Search</button>
// render the dropdown if value existed
{Boolean(keyword) && (
<div onClick={() => handleSearch('AUTHOR')}>{keyword} - Search in Author</div>
)}
Related