Filtering and Sorting Lists in React
×


Filtering and Sorting Lists in React

106

🔍 Filtering and Sorting Lists in React

When building data-heavy UIs like product catalogs, task managers, or dashboards, filtering and sorting are key interactions. With React’s powerful state management and JavaScript methods, implementing these features is simpler than you think! Let’s break it down step-by-step. ⚡

📋 Sample Dataset

Let’s use a basic list of users to demonstrate filtering and sorting:

const users = [
  { id: 1, name: "Alice", age: 25 },
  { id: 2, name: "Bob", age: 30 },
  { id: 3, name: "Charlie", age: 22 },
  { id: 4, name: "Daisy", age: 28 }
];

🔎 Filtering the List

We’ll filter users based on a search input for names:

const [search, setSearch] = useState("");

const filteredUsers = users.filter(user =>
  user.name.toLowerCase().includes(search.toLowerCase())
);

Now bind this search state to an input:

<input
  type="text"
  placeholder="Search users..."
  value={search}
  onChange={(e) => setSearch(e.target.value)}
/>

And render the filtered list:

<ul>
  {filteredUsers.map(user => (
    <li key={user.id}>{user.name} - {user.age}</li>
  ))}
</ul>

✅ Users will now be filtered in real-time as you type! ✨

🔃 Sorting the List

You can sort alphabetically, numerically, or by any property. Here’s how to sort users by name:

const sortedUsers = [...filteredUsers].sort((a, b) =>
  a.name.localeCompare(b.name)
);

To sort by age (ascending):

const sortedByAge = [...filteredUsers].sort((a, b) => a.age - b.age);

🔀 Toggle Sort Order

Let’s make the sorting interactive with a sort direction toggle:

const [sortAsc, setSortAsc] = useState(true);

const sortedUsers = [...filteredUsers].sort((a, b) => {
  return sortAsc
    ? a.name.localeCompare(b.name)
    : b.name.localeCompare(a.name);
});

Toggle the direction with a button:

<button onClick={() => setSortAsc(!sortAsc)}>
  Sort {sortAsc ? "Descending" : "Ascending"}
</button>

🧩 Full Example: Filter + Sort

const UserList = () => {
  const [search, setSearch] = useState("");
  const [sortAsc, setSortAsc] = useState(true);

  const filteredUsers = users.filter(user =>
    user.name.toLowerCase().includes(search.toLowerCase())
  );

  const sortedUsers = [...filteredUsers].sort((a, b) => {
    return sortAsc
      ? a.name.localeCompare(b.name)
      : b.name.localeCompare(a.name);
  });

  return (
    <div>
      <input
        type="text"
        placeholder="Search users..."
        value={search}
        onChange={(e) => setSearch(e.target.value)}
      />

      <button onClick={() => setSortAsc(!sortAsc)}>
        Sort {sortAsc ? "Descending" : "Ascending"}
      </button>

      <ul>
        {sortedUsers.map(user => (
          <li key={user.id}>
            {user.name} - {user.age}
          </li>
        ))}
      </ul>
    </div>
  );
};

💡 Real-World Applications

  • 📁 Filtering files or folders by name/type
  • 📦 Sorting products by price, rating, or popularity
  • 📊 Sorting dashboard data chronologically

⚠️ Tips & Gotchas

  • ✅ Always clone the array (using [...arr]) before sorting to avoid mutating original data
  • ✅ Chain filter() and sort() for clean logic
  • ✅ Use localeCompare() for strings and - for numbers

🧠 Recap

  • filter() is great for search-based or checkbox filters
  • sort() handles ordering — ascending or descending
  • Combining both gives powerful, dynamic interfaces

Filtering and sorting lists in React helps you deliver responsive, personalized UIs your users will love! 🔥

🚀 What’s Next?

  • Build a full-featured table with filters, sort, and pagination
  • Use React Table or TanStack Table for advanced grids
  • Add multi-criteria filters and dropdowns

With these tools, you're ready to handle any dynamic list challenge React throws your way. Let the data flow! 💪📊



If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!


Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat