Ojasa Mirai

Ojasa Mirai

ReactJS

Loading...

Learning Level

🟒 BeginnerπŸ”΅ Advanced
πŸ“‹ Rendering Lists with map()πŸ”‘ Keys and Reconciliation✨ Unique Keys⚠️ Common Key MistakesπŸ” Filtering Lists↕️ Sorting and Reorderingβž• Dynamic Lists
Reactjs/Lists Keys/Filtering Lists

πŸ” Filtering Lists

Understanding List Filtering

πŸ“‹ Filtering is showing only items that match certain criteria while hiding others. The JavaScript `filter()` method creates a new array containing only items where a test function returns true.

Filtering is different from mappingβ€”map transforms data, while filter selects which items to display.


Basic Filtering

Simple Filter Example

interface Product {
  id: number;
  name: string;
  category: string;
  price: number;
  inStock: boolean;
}

function ProductList() {
  const products: Product[] = [
    { id: 1, name: "Laptop", category: "Electronics", price: 999, inStock: true },
    { id: 2, name: "Coffee", category: "Beverages", price: 5, inStock: true },
    { id: 3, name: "Desk", category: "Furniture", price: 299, inStock: false },
    { id: 4, name: "Monitor", category: "Electronics", price: 399, inStock: true }
  ];

  // Filter for Electronics only
  const electronics = products.filter(product => product.category === "Electronics");

  return (
    <div>
      <h2>Electronics</h2>
      <ul>
        {electronics.map(product => (
          <li key={product.id}>
            {product.name} - ${product.price}
          </li>
        ))}
      </ul>
    </div>
  );
}

Filter Methods

function FilterExamples() {
  const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

  // Even numbers only
  const evenItems = items.filter(n => n % 2 === 0);

  // Numbers greater than 5
  const largeItems = items.filter(n => n > 5);

  // Custom predicate
  const selected = items.filter(n => n > 3 && n < 8);

  return <div>{/* Display filtered items */}</div>;
}

Dynamic Filtering with State

Search Filter

interface User {
  id: number;
  name: string;
  email: string;
  role: string;
}

function UserDirectory() {
  const [searchTerm, setSearchTerm] = React.useState("");

  const users: User[] = [
    { id: 1, name: "Alice Johnson", email: "alice@company.com", role: "Engineer" },
    { id: 2, name: "Bob Smith", email: "bob@company.com", role: "Designer" },
    { id: 3, name: "Carol White", email: "carol@company.com", role: "Engineer" },
    { id: 4, name: "David Brown", email: "david@company.com", role: "Manager" }
  ];

  // Filter users based on search term
  const filteredUsers = users.filter(user =>
    user.name.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <div>
      <input
        type="text"
        placeholder="Search users..."
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
        style={{ marginBottom: "20px", padding: "8px", width: "100%" }}
      />
      <ul>
        {filteredUsers.map(user => (
          <li key={user.id}>
            <strong>{user.name}</strong>
            <p>{user.email} - {user.role}</p>
          </li>
        ))}
      </ul>
    </div>
  );
}

Category Filter

interface Article {
  id: number;
  title: string;
  category: string;
  date: string;
}

function ArticleList() {
  const [selectedCategory, setSelectedCategory] = React.useState("All");

  const articles: Article[] = [
    { id: 1, title: "React Hooks Guide", category: "React", date: "2024-01-15" },
    { id: 2, title: "TypeScript Best Practices", category: "TypeScript", date: "2024-01-14" },
    { id: 3, title: "State Management", category: "React", date: "2024-01-13" },
    { id: 4, title: "Type Safety", category: "TypeScript", date: "2024-01-12" }
  ];

  const categories = ["All", ...new Set(articles.map(a => a.category))];

  const filteredArticles = selectedCategory === "All"
    ? articles
    : articles.filter(article => article.category === selectedCategory);

  return (
    <div>
      <div style={{ marginBottom: "20px" }}>
        {categories.map(category => (
          <button
            key={category}
            onClick={() => setSelectedCategory(category)}
            style={{
              marginRight: "10px",
              padding: "8px 16px",
              backgroundColor: selectedCategory === category ? "#0066cc" : "#f0f0f0",
              color: selectedCategory === category ? "white" : "black",
              border: "none",
              borderRadius: "4px",
              cursor: "pointer"
            }}
          >
            {category}
          </button>
        ))}
      </div>
      <ul>
        {filteredArticles.map(article => (
          <li key={article.id}>
            <h3>{article.title}</h3>
            <p>{article.category} - {article.date}</p>
          </li>
        ))}
      </ul>
    </div>
  );
}

Multiple Filters

interface Task {
  id: number;
  title: string;
  status: "pending" | "in-progress" | "completed";
  priority: "low" | "medium" | "high";
}

function TaskFilter() {
  const [statusFilter, setStatusFilter] = React.useState<string | null>(null);
  const [priorityFilter, setPriorityFilter] = React.useState<string | null>(null);

  const tasks: Task[] = [
    { id: 1, title: "Design mockups", status: "completed", priority: "high" },
    { id: 2, title: "Code review", status: "in-progress", priority: "high" },
    { id: 3, title: "Write tests", status: "pending", priority: "medium" },
    { id: 4, title: "Update docs", status: "pending", priority: "low" }
  ];

  // Apply both filters
  let filtered = tasks;

  if (statusFilter) {
    filtered = filtered.filter(task => task.status === statusFilter);
  }

  if (priorityFilter) {
    filtered = filtered.filter(task => task.priority === priorityFilter);
  }

  return (
    <div>
      <div style={{ marginBottom: "20px" }}>
        <label>
          Status:
          <select
            value={statusFilter || ""}
            onChange={(e) => setStatusFilter(e.target.value || null)}
            style={{ marginLeft: "10px" }}
          >
            <option value="">All</option>
            <option value="pending">Pending</option>
            <option value="in-progress">In Progress</option>
            <option value="completed">Completed</option>
          </select>
        </label>
        <label style={{ marginLeft: "20px" }}>
          Priority:
          <select
            value={priorityFilter || ""}
            onChange={(e) => setPriorityFilter(e.target.value || null)}
            style={{ marginLeft: "10px" }}
          >
            <option value="">All</option>
            <option value="low">Low</option>
            <option value="medium">Medium</option>
            <option value="high">High</option>
          </select>
        </label>
      </div>
      <ul>
        {filtered.map(task => (
          <li key={task.id}>
            {task.title} - {task.status} ({task.priority})
          </li>
        ))}
      </ul>
    </div>
  );
}

<details><summary>πŸ“š More Examples</summary>

Complex Filter Logic

interface Product {
  id: number;
  name: string;
  price: number;
  rating: number;
  inStock: boolean;
}

function SmartProductFilter() {
  const [minPrice, setMinPrice] = React.useState(0);
  const [maxPrice, setMaxPrice] = React.useState(1000);
  const [minRating, setMinRating] = React.useState(0);
  const [showOnlyInStock, setShowOnlyInStock] = React.useState(false);

  const products: Product[] = [
    { id: 1, name: "Product A", price: 50, rating: 4.5, inStock: true },
    { id: 2, name: "Product B", price: 150, rating: 3.8, inStock: false },
    { id: 3, name: "Product C", price: 300, rating: 4.8, inStock: true },
    { id: 4, name: "Product D", price: 75, rating: 3.2, inStock: true }
  ];

  const filtered = products.filter(product =>
    product.price >= minPrice &&
    product.price <= maxPrice &&
    product.rating >= minRating &&
    (!showOnlyInStock || product.inStock)
  );

  return (
    <div>
      <div style={{ marginBottom: "20px" }}>
        <label>
          Price: ${minPrice} - ${maxPrice}
          <input
            type="range"
            min="0"
            max="1000"
            value={maxPrice}
            onChange={(e) => setMaxPrice(Number(e.target.value))}
            style={{ marginLeft: "10px" }}
          />
        </label>
        <label style={{ marginLeft: "20px" }}>
          Min Rating: {minRating}
          <input
            type="range"
            min="0"
            max="5"
            step="0.5"
            value={minRating}
            onChange={(e) => setMinRating(Number(e.target.value))}
            style={{ marginLeft: "10px" }}
          />
        </label>
        <label style={{ marginLeft: "20px" }}>
          <input
            type="checkbox"
            checked={showOnlyInStock}
            onChange={(e) => setShowOnlyInStock(e.target.checked)}
          />
          In Stock Only
        </label>
      </div>
      <p>Found {filtered.length} products</p>
      <ul>
        {filtered.map(product => (
          <li key={product.id}>
            {product.name} - ${product.price} ⭐ {product.rating}
          </li>
        ))}
      </ul>
    </div>
  );
}

No Results State

function FilteredListWithEmpty() {
  const [search, setSearch] = React.useState("");
  const items = ["Apple", "Banana", "Cherry", "Date"];

  const filtered = items.filter(item =>
    item.toLowerCase().includes(search.toLowerCase())
  );

  return (
    <div>
      <input
        value={search}
        onChange={(e) => setSearch(e.target.value)}
        placeholder="Search..."
      />
      {filtered.length === 0 ? (
        <p>No items found matching "{search}"</p>
      ) : (
        <ul>
          {filtered.map((item, index) => (
            <li key={index}>{item}</li>
          ))}
        </ul>
      )}
    </div>
  );
}

</details>


Summary Table

Filter TypeMethodExample
Exact match`.filter(x => x.id === 5)`By ID or exact value
String search`.filter(x => x.name.includes(term))`Search/autocomplete
Range`.filter(x => x >= min && x <= max)`Price, age, score
Category`.filter(x => x.category === cat)`By category or type
Multiple`.filter(x => cond1 && cond2 && cond3)`Multiple criteria
Exclude`.filter(x => x.status !== "deleted")`Hide certain items

βœ… Key Takeaways

1. βœ… Use `array.filter()` to create a new array with only matching items

2. βœ… Filter creates a new arrayβ€”doesn't modify the original

3. βœ… Combine filter with map to both select and display items

4. βœ… Use filter with state for dynamic, user-driven filtering

5. βœ… Keep filter logic separate from rendering logic

6. βœ… Remember that filtering doesn't change the key stability

7. βœ… Use meaningful filter conditions that are easy to understand

8. βœ… Handle empty filtered results gracefully

9. βœ… Multiple filters can be chained or combined with &&

10. βœ… Filtering UI can use checkboxes, selects, or search inputs


πŸŽ“ Next Steps

Now let's learn how to sort and reorder lists.

β†’ Learn about Sorting and Reordering

Challenge: Build a filtered product list


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep β€’ Build Real β€’ Verify Skills β€’ Launch Forward

Courses

PythonFastapiReactJSCloud

Β© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn