I recently recreated a website that has a search filter that narrows down a list of search results as the user types. The code in the markup of the component looks like this
<label for="searchBar" className={`srcryBox ${styles.searchLabel}`}>
<input
id="searchBar"
type="search"
className={ styles.searchBar }
placeholder="search for groups"
onKeyUp={ ( event ) => detectEnterKey( event ) }
onChange={ ( event ) => handleKeyStrokes( event.target.value ) }
/>
<button
type="button"
className={ styles.searchButton }
onClick={ handleSearch }
>
search
</button>
</label>
As you can see I use the onKeyup
method to detect if the enter
key is pressed which I use to perform a search and the onChange
method to detect the current value inside the input. I also use an onClick
event on a button to detect when the user taps it so a search is performed on the text they entered into the search bar. The detectEnterKey
function just checks the event.key
value and if it equals Enter
it passes the current search value up to the parent component to filter results that match or start with the characters in the text. The handleKeyStrokes
function updates a useState()
hook with the current value of the search bar which is what gets passed up to the parent when the Enter
key is detected in the detectEnterKey
function. The handleSearch
function also passes the current value up to the parent through the same prop when clicked.
Everything works perfectly fine on a computer with a keyboard. As I type I can see the search results narrowing down in the pane I have beneath the search bar. When I press enter
or click the search
button the search results appear or my no results
text. However on mobile devices nothing happens as I type or press the return
key and the search button doesn’t seem to do anything which I’m guessing is because the value in the search bar isn’t being updated through the onChange
method.
I’ve been googling everything I can think of to try to find relevant info on this issue and have come across a few results where people were having this problem however they were using jquery or java. I looked into the touch api for javascript but it was a lot of stuff mainly about detecting where a user touches on the screen and being able to move draggable elements around. Is there a way to detect events from a mobile keyboard in javascript?