React / React Lists / Filtering Lists
Home /React /React Lists /Filtering Lists

Filtering Lists

Filtering Lists

Filtering means showing only a subset of list items that match a specific condition. In React, you chain .filter() before .map() to first narrow the array down to matching items, then transform those into JSX. The .filter() method returns a new array containing only elements for which the callback returns true.

Static Filter: Show Only Published Courses

JSX

const courses = [
  { id: 1, title: 'React Basics',    status: 'published', level: 'Beginner'     },
  { id: 2, title: 'Advanced Hooks',  status: 'draft',     level: 'Advanced'     },
  { id: 3, title: 'Node.js Crash',  status: 'published', level: 'Intermediate' },
  { id: 4, title: 'SEO Essentials', status: 'draft',     level: 'Beginner'     },
];

function PublishedCourses() {
  return (
    <ul>
      {courses
        // Step 1: keep only published courses
        .filter((c) => c.status === 'published')
        // Step 2: render the filtered results
        .map((c) => (
          <li key={c.id}>{c.title}{c.level}</li>
        ))}
    </ul>
  );
}

/* Output:
   • React Basics — Beginner
   • Node.js Crash — Intermediate
*/

Dynamic Filter: Search Input + Category Dropdown

DynamicFilter.jsx

JSX

import { useState } from 'react';

function CourseSearch({ courses }) {
  const [query,    setQuery]    = useState('');
  const [category, setCategory] = useState('All');

  const categories = ['All', 'Frontend', 'Backend', 'Design', 'Marketing'];

  // Derived value: filter runs on every render based on current state
  const filtered = courses
    .filter((c) => {
      const matchesQuery    = c.title.toLowerCase().includes(query.toLowerCase());
      const matchesCategory = category === 'All' || c.category === category;
      return matchesQuery && matchesCategory;
    });

  return (
    <div>
      {/* Search Input */}
      <input
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        placeholder="Search courses..."
      />

      {/* Category Tabs */}
      <div className="tabs">
        {categories.map((cat) => (
          <button
            key={cat}
            className={cat === category ? 'active' : ''}
            onClick={() => setCategory(cat)}
          >{cat}</button>
        ))}
      </div>

      {/* Results */}
      {filtered.length === 0 ? (
        <p>No courses found.</p>
      ) : (
        <ul>
          {filtered.map((c) => (
            <li key={c.id}>{c.title}</li>
          ))}
        </ul>
      )}
    </div>
  );
}