
Filtering, Searching, and Sorting in React
Filtering, searching, and sorting are essential data manipulation techniques in React applications that enhance user experience by allowing users to easily find and organize information. These operations typically involve managing data in the component's state and dynamically updating the rendered output based on user input.
1. Filtering
Definition:
Display only the items that meet certain criteria (e.g., category, status, range).
Example: Filter by role
const users = [
{ id: 1, name: 'John', role: 'admin' },
{ id: 2, name: 'Jane', role: 'user' },
{ id: 3, name: 'Alex', role: 'admin' },
];
const [filterRole, setFilterRole] = useState('all');
const filteredUsers = filterRole === 'all'
? users
: users.filter(user => user.role === filterRole);
<select onChange={(e) => setFilterRole(e.target.value)}>
<option value="all">All</option>
<option value="admin">Admin</option>
<option value="user">User</option>
</select>
<ul>
{filteredUsers.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
2. Searching
Definition:
Find items by matching part of the content (e.g., name, title, description).
Example: Search by name
const [searchTerm, setSearchTerm] = useState('');
const searchedUsers = users.filter(user =>
user.name.toLowerCase().includes(searchTerm.toLowerCase())
);
<input
type="text"
placeholder="Search user"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
<ul>
{searchedUsers.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
3. Sorting
Definition:
Reorder data based on a field (alphabetical, numerical, date, etc.).
Example: Sort by name
const [sortOrder, setSortOrder] = useState('asc');
const sortedUsers = [...users].sort((a, b) => {
if (sortOrder === 'asc') return a.name.localeCompare(b.name);
else return b.name.localeCompare(a.name);
});
<button onClick={() => setSortOrder('asc')}>Sort A-Z</button>
<button onClick={() => setSortOrder('desc')}>Sort Z-A</button>
<ul>
{sortedUsers.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
Combine All Three (Search + Filter + Sort)
const processedUsers = users
.filter(user => filterRole === 'all' || user.role === filterRole)
.filter(user => user.name.toLowerCase().includes(searchTerm.toLowerCase()))
.sort((a, b) =>
sortOrder === 'asc' ? a.name.localeCompare(b.name) : b.name.localeCompare(a.name)
);
Summary Table
Feature | Purpose | Common Usage |
---|---|---|
Filtering | Show items by category/condition | Dropdowns, tags |
Searching | Match items by text input | Search bars |
Sorting | Order items by field | Buttons, headers (A-Z, price etc) |
Comments
Add new comment