Push a new state when query box is emptied

This commit is contained in:
Shuqi 2024-05-06 17:37:09 +08:00
parent bdd51f040d
commit 69dd836ba4
1 changed files with 24 additions and 1 deletions

View File

@ -14,6 +14,11 @@ function App() {
function queryOnChange () { function queryOnChange () {
let query = inputSearch.current.value let query = inputSearch.current.value
query = query.replace(/[^a-zA-Z0-9\- ]/, "") query = query.replace(/[^a-zA-Z0-9\- ]/, "")
if (query == '') {
history.pushState('', '', '#')
}
setCurrentQuery(query) setCurrentQuery(query)
dispatch(setQuery(query)) dispatch(setQuery(query))
} }
@ -27,15 +32,33 @@ function App() {
dispatch(setShowName(checkShowName.current.checked)) dispatch(setShowName(checkShowName.current.checked))
} }
function confirmKeyword (e) {
if (e.key === 'Enter') {
history.pushState('', '', '#' + inputSearch.current.value)
inputSearch.current.blur()
}
}
const handleHashChange = (e) => {
// console.log(e)
inputSearch.current.value = window.location.hash.replace("#", "")
queryOnChange()
};
useEffect(() => { useEffect(() => {
inputSearch.current.focus() inputSearch.current.focus()
queryOnChange() queryOnChange()
window.addEventListener('hashchange', handleHashChange)
return () => {
window.removeEventListener('hashchange', handleHashChange)
}
}) })
return ( return (
<> <>
<div className="pixel-input"> <div className="pixel-input">
<input type='text' id='search' ref={ inputSearch } onChange={ queryOnChange } value={ currentQuery } placeholder="Search an icon — try 'animal', 'fruit', 'logo', 'ui' or 'red'" autoComplete='no' /> <input type='text' id='search' ref={ inputSearch } onChange={ queryOnChange } onKeyDown={ confirmKeyword } value={ currentQuery } placeholder="Search an icon — try 'animal', 'fruit', 'logo', 'ui' or 'red'" autoComplete='no' />
{ {
currentQuery == '' ? '' : <button id='btn-clear-search' onClick={ clearQuery }>x</button> currentQuery == '' ? '' : <button id='btn-clear-search' onClick={ clearQuery }>x</button>
} }