A good[ish] website
Web development blog, loads of UI and JavaScript topics
This post looks into how to make a list which has a search field, so that the user filter the list.
This is what we’re building:
Here’s code for that example, I’ve added explanations below for the highlighted lines:
const listItems = ['foo', 'bar', 'baz', 'quix']
const FilterableList = () => {
const [searchResults, setSearchResults] = useState(listItems)
const handleChange = event => {
const value = event.target.value.toLowerCase()
if (value) {
const filteredItems = listItems.filter(item => item.toLowerCase().includes(value) )
setSearchResults(
filteredItems.length > 0 || value ? filteredItems : listItems )
} else {
setSearchResults(listItems) }
}
return (
<Wrap>
<Input onChange={handleChange} placeholder="Search" type="text" />
<ul>
{searchResults.length < 1 ? (
<li>No results</li> ) : (
searchResults.map(item => <li key={item}>{item}</li>) )}
</ul>
</Wrap>
)
}
listItems
, not the data in the state.Hope you’re still reading, because this is important.
We need to tell screen readers to announce the changes that have happened on the page when filtering. This can be done by defining the list as an ARIA live region, see the highlighted lines and the explanation below:
<>
<Input
aria-controls="tag-list" aria-label="search" onChange={handleChange}
placeholder="Search"
type="text"
/>
<ul aria-live="polite" id="tag-list" role="region"> {searchResults.length < 1 ? (
<li>No results</li>
) : (
searchResults.map(item => <li key={item}>{item}</li>)
)}
</ul>
</>
tag-list
.assertive
or off
.The region role is used to identify document areas the author deems significant. It is a generic landmark available to aid in navigation when none of the other landmark roles are appropriate.Read more about regions.
It’s just bliss to build stuff like this with React, it was made for this stuff. Also this is one of the cases where you need to keep accessibility in mind, because the basic HTML itself isn’t enough but you need to add some ARIA attributes.
Comments would go here, but the commenting system isn’t ready yet, sorry.