Skip to content

Instantly share code, notes, and snippets.

@ianks
Last active July 25, 2022 22:38
Show Gist options
  • Save ianks/52bd219743f450230524a60e72c287ed to your computer and use it in GitHub Desktop.
Save ianks/52bd219743f450230524a60e72c287ed to your computer and use it in GitHub Desktop.
// Overly complicated search form which uses custom state management 👎
function SearchBox() {
const [queryParams, setQueryParams] = useState({ showAllResults: false });
const handleSearchChange = (ev) => {
const eventValue = ev.target.value;
setQueryParams({ ...queryParams, q: eventValue });
}
const handleShowAllResultsToggle = (ev) => {
setQueryParams({ ...queryParams, showAllResults: ev.target.checked });
}
const navigateToNewPage = (ev) => {
history.push(`/search?q=${queryParams.q}&showAllResults=${queryParams.showAllResults}`)
}
return (
<div className="search-box">
<input type="search" placeholder="Search for blog posts" onChange={handleChange} />
<label>
Show all results?
<input type="checkbox" onChange={handleShowAllResultsToggle} />
</label>
<button onClick={navigateToNewPage}>
Search
</button>
</div>
)
}
// Simple search form which lets the browser do the heavy lifting 👍
function SearchBox() {
return (
<form action="/search" method="GET">
<input name="q" type="search" placeholder="Search for blog posts" />
<label>
Show all results?
<input name="showAllResults" type="checkbox" defaultValue={false} />
</label>
<button type="submit">
Search
</button>
</div>
)
}
@javiermiz
Copy link

Hello! Nice article, just to mention on line 21 the function should be handleSearchChange

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment