Popular Searches
Popular Course Categories
Popular Courses

Filtering Lists

Filtering Lists

Lists and Dynamic Rendering

Filtering Lists in React JS

Topic: Filtering Lists in React JS

Filtering lists is an important React JS concept used to display only those items that match a particular condition. In real-world applications, lists may contain hundreds or thousands of records, but users often need to find specific information quickly. React developers commonly use JavaScript's filter() method to select matching data and map() to render the filtered results as JSX elements.


1. What Is Filtering Lists in React?

Filtering lists means selecting specific items from an array based on a condition and displaying only the matching items in the user interface.

For example, an application may contain a list of students with different marks. If we want to display only students who scored 60 or more marks, we can filter the array and render the selected students.

Example of Student Data

const students = [
  { id: 1, name: "Rahul", marks: 85 },
  { id: 2, name: "Priya", marks: 92 },
  { id: 3, name: "Amit", marks: 45 },
  { id: 4, name: "Neha", marks: 76 }
];

In this example, filtering students by marks greater than or equal to 60 returns Rahul, Priya, and Neha. Amit is excluded because his marks are below 60.


2. Why Is Filtering Important in React?

  • Search functionality: Helps users find products, students, employees, or articles.
  • Category selection: Displays items belonging to a particular category.
  • Status filtering: Shows active, completed, pending, or cancelled records.
  • Data organization: Makes large collections easier to navigate.
  • Better user experience: Displays relevant information instead of unnecessary records.
  • Dynamic interfaces: Updates visible results when users change search text or filter options.
  • Real-world applications: Supports e-commerce product filters, employee directories, dashboards, and task management systems.

3. Understanding the JavaScript filter() Method

The filter() method creates a new array containing only those elements for which the callback function returns true. Items for which the callback returns false are excluded.

Syntax

const filteredArray = originalArray.filter((item) => {
  return condition;
});

Important Parts

  • originalArray: The original collection of items.
  • filter(): The JavaScript array method that selects matching items.
  • item: The current item being checked.
  • condition: An expression that evaluates to true or false.
  • filteredArray: A new array containing only matching items.

Simple Example

const numbers = [10, 15, 20, 25, 30];

const result = numbers.filter((number) => number > 20);

console.log(result);

// Output:
// [25, 30]

The callback checks every number. Only 25 and 30 satisfy the condition, so those numbers are included in the new array.


4. Filtering Lists in React Using filter() and map()

In React, filtering and rendering are commonly combined. First, filter() selects the matching records. Then, map() converts those records into JSX elements.

Example: Display Students Who Passed

function StudentList() {
  const students = [
    { id: 1, name: "Rahul", marks: 85 },
    { id: 2, name: "Priya", marks: 92 },
    { id: 3, name: "Amit", marks: 45 },
    { id: 4, name: "Neha", marks: 76 }
  ];

  const passedStudents = students.filter(
    (student) => student.marks >= 50
  );

  return (
    <div>
      <h2>Passed Students</h2>
      <ul>
        {passedStudents.map((student) => (
          <li key={student.id}>
            {student.name} - {student.marks} marks
          </li>
        ))}
      </ul>
    </div>
  );
}

export default StudentList;

Expected Output

Passed Students
Rahul - 85 marks
Priya - 92 marks
Neha - 76 marks

Explanation: The filter() method removes students with marks below 50 from the displayed results. The map() method then renders each remaining student. The key attribute helps React identify each list item.


5. Filtering an Array of Objects

Most real-world React lists contain objects rather than simple values. Each object can have multiple properties, such as name, price, category, status, or location. The filter condition can check any of these properties.

Example: Filter Products by Price

const products = [
  { id: 1, name: "Laptop", price: 55000 },
  { id: 2, name: "Mouse", price: 700 },
  { id: 3, name: "Keyboard", price: 1800 },
  { id: 4, name: "Monitor", price: 12000 }
];

const affordableProducts = products.filter(
  (product) => product.price < 5000
);

console.log(affordableProducts);

Result: The filtered array contains the Mouse and Keyboard objects because their prices are below ₹5,000.

Rendering the Filtered Products

function AffordableProducts() {
  const products = [
    { id: 1, name: "Laptop", price: 55000 },
    { id: 2, name: "Mouse", price: 700 },
    { id: 3, name: "Keyboard", price: 1800 },
    { id: 4, name: "Monitor", price: 12000 }
  ];

  const affordableProducts = products.filter(
    (product) => product.price < 5000
  );

  return (
    <div>
      <h2>Affordable Products</h2>
      {affordableProducts.map((product) => (
        <div key={product.id}>
          <h3>{product.name}</h3>
          <p>Price: ₹{product.price}</p>
        </div>
      ))}
    </div>
  );
}

export default AffordableProducts;

6. Filtering Lists Using React State

React state allows users to change filtering criteria while interacting with the application. For example, a user can select a category or type a search term, and React will update the displayed list.

When the state changes, React re-renders the component and calculates the filtered results again.

Example: Search Students by Name

import { useState } from "react";

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

  const students = [
    { id: 1, name: "Rahul" },
    { id: 2, name: "Priya" },
    { id: 3, name: "Amit" },
    { id: 4, name: "Neha" }
  ];

  const filteredStudents = students.filter((student) =>
    student.name.toLowerCase().includes(search.toLowerCase())
  );

  return (
    <div>
      <h2>Search Students</h2>

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

      <ul>
        {filteredStudents.map((student) => (
          <li key={student.id}>{student.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default StudentSearch;

How It Works

  1. useState("") creates a state variable to store the search text.
  2. The input's value is connected to the search state.
  3. The onChange event updates the state whenever the user types.
  4. filter() checks whether each student's name contains the search text.
  5. toLowerCase() makes the search case-insensitive.
  6. map() renders the matching students.

For example, entering rah displays Rahul. Clearing the input displays all students again.


7. Filtering Lists with Multiple Conditions

Sometimes a list needs to satisfy more than one condition. You can combine conditions using logical operators such as && (AND) and || (OR).

Example: Filter Products by Price and Category

const products = [
  { id: 1, name: "Laptop", category: "Electronics", price: 55000 },
  { id: 2, name: "Mouse", category: "Electronics", price: 700 },
  { id: 3, name: "Chair", category: "Furniture", price: 3500 },
  { id: 4, name: "Desk", category: "Furniture", price: 8000 }
];

const filteredProducts = products.filter(
  (product) =>
    product.category === "Furniture" &&
    product.price < 5000
);

console.log(filteredProducts);

// Result: Chair

In this example, a product must belong to the Furniture category and cost less than ₹5,000. Both conditions must be true.

Using the OR Operator

const selectedProducts = products.filter(
  (product) =>
    product.category === "Furniture" ||
    product.price < 1000
);

The OR operator includes a product if at least one condition is true.


8. Filtering Lists by Category

Category filtering allows users to select a group of items, such as electronics, clothing, furniture, or accessories.

Example: Category Filter Buttons

import { useState } from "react";

function ProductCategories() {
  const [category, setCategory] = useState("All");

  const products = [
    { id: 1, name: "Laptop", category: "Electronics" },
    { id: 2, name: "Phone", category: "Electronics" },
    { id: 3, name: "Chair", category: "Furniture" },
    { id: 4, name: "Desk", category: "Furniture" }
  ];

  const filteredProducts = products.filter((product) =>
    category === "All" || product.category === category
  );

  return (
    <div>
      <h2>Product Categories</h2>

      <button onClick={() => setCategory("All")}>All</button>
      <button onClick={() => setCategory("Electronics")}>
        Electronics
      </button>
      <button onClick={() => setCategory("Furniture")}>
        Furniture
      </button>

      {filteredProducts.map((product) => (
        <div key={product.id}>
          <p>{product.name} - {product.category}</p>
        </div>
      ))}
    </div>
  );
}

export default ProductCategories;

Explanation: The state variable category stores the selected category. Selecting a button updates the state, and the filter condition determines which products are displayed. Selecting All shows every product.


9. Filtering Lists with a Dropdown

A dropdown is another common way to select a filtering option. It is useful when an application has several categories or statuses.

import { useState } from "react";

function EmployeeFilter() {
  const [department, setDepartment] = useState("All");

  const employees = [
    { id: 1, name: "Rahul", department: "Development" },
    { id: 2, name: "Priya", department: "Design" },
    { id: 3, name: "Amit", department: "Development" },
    { id: 4, name: "Neha", department: "Testing" }
  ];

  const filteredEmployees = employees.filter((employee) =>
    department === "All" || employee.department === department
  );

  return (
    <div>
      <h2>Employee Directory</h2>

      <label htmlFor="department">Select Department: </label>
      <select
        id="department"
        value={department}
        onChange={(event) => setDepartment(event.target.value)}
      >
        <option value="All">All Departments</option>
        <option value="Development">Development</option>
        <option value="Design">Design</option>
        <option value="Testing">Testing</option>
      </select>

      {filteredEmployees.map((employee) => (
        <div key={employee.id}>
          <h3>{employee.name}</h3>
          <p>Department: {employee.department}</p>
        </div>
      ))}
    </div>
  );
}

export default EmployeeFilter;

This example uses a controlled dropdown. When the selected department changes, React displays only employees in that department.


10. Filtering Lists by Status

Status filters are useful in task managers, order tracking applications, and project dashboards.

Example: Task Status Filter

import { useState } from "react";

function TaskList() {
  const [status, setStatus] = useState("All");

  const tasks = [
    { id: 1, title: "Learn React", completed: true },
    { id: 2, title: "Build a project", completed: false },
    { id: 3, title: "Practice JavaScript", completed: true },
    { id: 4, title: "Review components", completed: false }
  ];

  const filteredTasks = tasks.filter((task) => {
    if (status === "Completed") return task.completed;
    if (status === "Active") return !task.completed;
    return true;
  });

  return (
    <div>
      <h2>Task List</h2>

      <button onClick={() => setStatus("All")}>All</button>
      <button onClick={() => setStatus("Active")}>Active</button>
      <button onClick={() => setStatus("Completed")}>Completed</button>

      <ul>
        {filteredTasks.map((task) => (
          <li key={task.id}>
            {task.title} - {task.completed ? "Completed" : "Active"}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default TaskList;

The filter condition checks the selected status and returns only the tasks that match it. The All option returns every task.


11. Filtering and Sorting Lists Together

Filtering selects matching records, while sorting changes their order. These operations can be combined to show relevant results in a preferred order.

const products = [
  { id: 1, name: "Laptop", price: 55000 },
  { id: 2, name: "Mouse", price: 700 },
  { id: 3, name: "Keyboard", price: 1800 },
  { id: 4, name: "Monitor", price: 12000 }
];

const results = products
  .filter((product) => product.price < 20000)
  .sort((a, b) => a.price - b.price);

console.log(results);

The code first filters out products costing ₹20,000 or more. It then sorts the remaining products from lowest to highest price.

Important: In this example, filter() returns a new array, and sort() modifies that filtered array rather than the original products array. If sorting the original array directly, create a copy first.


12. Showing a Message When No Results Are Found

A search or filter may return an empty array. Instead of displaying a blank section, show a helpful message.

function FilteredProducts({ products, search }) {
  const filteredProducts = products.filter((product) =>
    product.name.toLowerCase().includes(search.toLowerCase())
  );

  return (
    <div>
      {filteredProducts.length === 0 ? (
        <p>No products found. Try another search.</p>
      ) : (
        <ul>
          {filteredProducts.map((product) => (
            <li key={product.id}>{product.name}</li>
          ))}
        </ul>
      )}
    </div>
  );
}

The conditional expression checks the length of the filtered array. If the array is empty, React displays the message; otherwise, it renders the matching products.


13. Filtering Lists from API Data

React applications often retrieve arrays of objects from APIs. Once the data is stored in state, you can filter it just like a locally defined array.

import { useEffect, useState } from "react";

function UserDirectory() {
  const [users, setUsers] = useState([]);
  const [search, setSearch] = useState("");
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    async function loadUsers() {
      try {
        const response = await fetch(
          "https://jsonplaceholder.typicode.com/users"
        );

        if (!response.ok) {
          throw new Error("Unable to load users");
        }

        const data = await response.json();
        setUsers(data);
      } catch (err) {
        setError(err.message || "Something went wrong");
      } finally {
        setLoading(false);
      }
    }

    loadUsers();
  }, []);

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

  if (loading) return <p>Loading users...</p>;
  if (error) return <p role="alert">{error}</p>;

  return (
    <div>
      <h2>User Directory</h2>

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

      {filteredUsers.length === 0 ? (
        <p>No matching users found.</p>
      ) : (
        filteredUsers.map((user) => (
          <div key={user.id}>
            <h3>{user.name}</h3>
            <p>{user.email}</p>
          </div>
        ))
      )}
    </div>
  );
}

export default UserDirectory;

How It Works

  1. useEffect() starts the API request when the component mounts.
  2. fetch() retrieves the user data.
  3. setUsers(data) stores the returned array in React state.
  4. The search input updates the search state.
  5. filter() selects users whose names match the search text.
  6. The component renders the matching users and handles loading, errors, and empty results.

Always verify the API response structure before filtering it. The example assumes the endpoint returns an array of user objects.


14. Filtering Lists by Numbers and Ranges

Number-based filtering is commonly used for prices, marks, ratings, ages, and quantities.

Example: Filter Students by Minimum Marks

const students = [
  { id: 1, name: "Rahul", marks: 85 },
  { id: 2, name: "Priya", marks: 92 },
  { id: 3, name: "Amit", marks: 45 },
  { id: 4, name: "Neha", marks: 76 }
];

const highScorers = students.filter(
  (student) => student.marks >= 80
);

Example: Filter Products Within a Price Range

const budgetProducts = products.filter(
  (product) => product.price >= 500 && product.price <= 5000
);

The first example selects students who scored at least 80 marks. The second selects products priced between ₹500 and ₹5,000, including both boundaries.


15. Filtering Lists with Case-Insensitive Search

Case-insensitive search treats uppercase and lowercase letters as equivalent. Converting both the search text and the item text to lowercase makes the comparison easier.

const search = "react";

const courses = [
  { id: 1, name: "React JS" },
  { id: 2, name: "JavaScript" },
  { id: 3, name: "React Native" },
  { id: 4, name: "HTML and CSS" }
];

const results = courses.filter((course) =>
  course.name.toLowerCase().includes(search.toLowerCase())
);

The results contain React JS and React Native because their names include the search term, regardless of letter case.


16. Filtering Lists with Checkboxes

A checkbox can enable or disable a filter. This is useful when users want to show only available products, passed students, or active tasks.

import { useState } from "react";

function AvailableProducts() {
  const [availableOnly, setAvailableOnly] = useState(false);

  const products = [
    { id: 1, name: "Laptop", available: true },
    { id: 2, name: "Headphones", available: false },
    { id: 3, name: "Keyboard", available: true }
  ];

  const filteredProducts = products.filter(
    (product) => !availableOnly || product.available
  );

  return (
    <div>
      <h2>Products</h2>

      <label>
        <input
          type="checkbox"
          checked={availableOnly}
          onChange={(event) => setAvailableOnly(event.target.checked)}
        />
        Show available products only
      </label>

      {filteredProducts.map((product) => (
        <p key={product.id}>
          {product.name} - {product.available ? "Available" : "Unavailable"}
        </p>
      ))}
    </div>
  );
}

export default AvailableProducts;

When the checkbox is selected, only available products are displayed. When it is unchecked, all products are shown.


17. Filtering State Arrays Without Mutating Them

React state should be treated as immutable. The filter() method is useful for producing a new array when you need to remove items from a list stored in state.

Example: Remove an Item from a List

import { useState } from "react";

function ShoppingList() {
  const [items, setItems] = useState([
    { id: 1, name: "Milk" },
    { id: 2, name: "Bread" },
    { id: 3, name: "Eggs" }
  ]);

  function removeItem(id) {
    setItems((currentItems) =>
      currentItems.filter((item) => item.id !== id)
    );
  }

  return (
    <ul>
      {items.map((item) => (
        <li key={item.id}>
          {item.name}
          <button onClick={() => removeItem(item.id)}>
            Remove
          </button>
        </li>
      ))}
    </ul>
  );
}

export default ShoppingList;

Explanation: Clicking Remove filters out the item whose ID matches the selected ID. The state setter receives a new array, and React re-renders the updated list.


18. Common Mistakes When Filtering Lists

Mistake Why It Is a Problem Solution
Using map() instead of filter() to select records map() transforms every item rather than excluding nonmatching items. Use filter() to select matching items, then map() to render them.
Forgetting to return a condition A callback with a block body may return undefined for every item. Use an explicit return or an expression-bodied arrow function.
Using the wrong property name The condition may never match the intended records. Check the structure and spelling of each object's properties.
Comparing values with the wrong type Strings and numbers may behave differently in comparisons. Normalize or validate data types before comparing.
Ignoring letter case in search Search results may differ depending on capitalization. Use toLowerCase() on both values when appropriate.
Not handling an empty result The user may see a blank area. Show a “No results found” message.
Mutating state arrays directly Direct mutation can prevent React from reliably detecting changes. Use filter() to create a new array and update state.
Missing keys in rendered lists React may display a missing-key warning. Use a stable, unique key such as key={item.id}.
Filtering before asynchronous data is ready The data may initially be unavailable or have an unexpected shape. Initialize state appropriately and handle loading and errors.

19. Difference Between filter() and map()

Feature filter() map()
Purpose Selects items that satisfy a condition. Transforms every item into a new result.
Return value A new array containing matching original items. A new array containing callback results.
Changes array length May produce fewer items than the original array. Normally produces one result per original item.
Common React use Search, category selection, and status filtering. Creating JSX elements from data.
Example items.filter(item => item.active) items.map(item => <li key={item.id}>{item.name}</li>)

A common React pattern is to use filter() first and map() second.

const activeItems = items.filter((item) => item.active);

const listElements = activeItems.map((item) => (
  <li key={item.id}>{item.name}</li>
));

20. Mini Project: Product Filtering Application

Project objective: Build a simple product listing interface that supports searching by name, filtering by category, and displaying matching products.

Complete React Example

import { useState } from "react";

function ProductFilterApp() {
  const [search, setSearch] = useState("");
  const [category, setCategory] = useState("All");

  const products = [
    { id: 1, name: "Laptop", category: "Electronics", price: 55000 },
    { id: 2, name: "Mouse", category: "Accessories", price: 700 },
    { id: 3, name: "Keyboard", category: "Accessories", price: 1800 },
    { id: 4, name: "Smartphone", category: "Electronics", price: 25000 },
    { id: 5, name: "Desk Chair", category: "Furniture", price: 4500 }
  ];

  const filteredProducts = products.filter((product) => {
    const matchesSearch = product.name
      .toLowerCase()
      .includes(search.toLowerCase());

    const matchesCategory =
      category === "All" || product.category === category;

    return matchesSearch && matchesCategory;
  });

  return (
    <div>
      <h1>Product Filtering App</h1>

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

      <select
        value={category}
        onChange={(event) => setCategory(event.target.value)}
      >
        <option value="All">All Categories</option>
        <option value="Electronics">Electronics</option>
        <option value="Accessories">Accessories</option>
        <option value="Furniture">Furniture</option>
      </select>

      <p>Products found: {filteredProducts.length}</p>

      {filteredProducts.length === 0 ? (
        <p>No products match your filters.</p>
      ) : (
        <div>
          {filteredProducts.map((product) => (
            <div key={product.id}>
              <h3>{product.name}</h3>
              <p>Category: {product.category}</p>
              <p>Price: ₹{product.price}</p>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

export default ProductFilterApp;

Features of This Project

  • Search products by name.
  • Filter products by category.
  • Combine multiple filter conditions.
  • Display the number of matching products.
  • Show a message when no products match.
  • Use stable keys for every rendered product.
  • Update results when input or category state changes.

Suggested Improvements

  1. Add minimum and maximum price filters.
  2. Add sorting by price or name.
  3. Add an “In Stock” checkbox.
  4. Move product data into state or fetch it from an API.
  5. Add CSS styling for product cards.

21. Interview Questions and Answers

Q1. What is filtering in React?

Answer: Filtering in React means selecting items from an array based on a condition and displaying only those items in the user interface.

Q2. Which JavaScript method is used to filter an array?

Answer: The filter() method returns a new array containing elements for which the callback function returns true.

Q3. Does filter() modify the original array?

Answer: No. The filter() method creates a new array. It does not remove items from the original array.

Q4. Can filter() be used with arrays of objects?

Answer: Yes. The callback can check object properties, such as product.price, student.marks, or user.name.

Q5. Why do developers combine filter() and map()?

Answer: filter() selects the required data, and map() converts the selected data into JSX elements.

Q6. How can you implement search functionality in React?

Answer: Store the search text in state, update it through an input's onChange event, and use filter() to select items that match the search text.

Q7. How can you filter by more than one condition?

Answer: Combine conditions using logical operators such as && and || inside the filter callback.

Q8. What happens when no items match the filter?

Answer: The filtered array is empty. You can check its length and display a message such as “No results found.”

Q9. How do you remove an item from a React state array?

Answer: Use filter() to create a new array that excludes the selected item, then pass the new array to the state setter.

Q10. Is filtering automatically performed by React?

Answer: No. Filtering is normally performed using JavaScript methods such as filter(). React renders the output based on the resulting data and current state.

Q11. How do you make a text search case-insensitive?

Answer: Convert both the search text and the property being searched to lowercase using toLowerCase() before comparing them.

Q12. Can you combine filtering and sorting?

Answer: Yes. You can filter the data first and then sort the filtered array before rendering it.


22. Practice Exercises

  1. Create a list of ten students and display only students who scored 70 or more marks.
  2. Create a product search input that filters products by name.
  3. Build category filter buttons for Electronics, Furniture, and Accessories.
  4. Filter employees according to their department.
  5. Create a task list with All, Active, and Completed filters.
  6. Filter products that cost between ₹1,000 and ₹10,000.
  7. Implement case-insensitive search for course names.
  8. Combine search and category filtering in the same component.
  9. Display a message when a filter returns no matching items.
  10. Create a shopping list where users can remove items using filter() and React state.
  11. Fetch users from an API and add a search field to filter the results.
  12. Add sorting by price to the product filtering project.

23. Best Practices for Filtering Lists

  • Use filter() to select records and map() to render them.
  • Keep filtering conditions clear and readable.
  • Use React state for interactive search fields and filter controls.
  • Use stable, unique keys when rendering the filtered results.
  • Handle empty arrays and no-result situations.
  • Validate data before filtering API responses.
  • Avoid mutating arrays stored in React state.
  • Normalize text when case-insensitive searching is required.
  • Use multiple conditions carefully to avoid unintended results.
  • Keep reusable filtering logic in a separate function when it improves maintainability.
  • For very large data sets, consider server-side filtering or pagination rather than downloading every record.

24. Quick Revision Checklist

  • Understand the purpose of list filtering in React.
  • Know the syntax and behavior of the JavaScript filter() method.
  • Filter arrays of objects by their properties.
  • Combine filter() and map() to display matching results.
  • Use useState() for interactive filtering.
  • Implement text search, category selection, and status filters.
  • Combine conditions with logical operators.
  • Handle empty results and API loading states.
  • Remove items from state arrays without mutating them.
  • Use stable keys and follow React list-rendering best practices.

25. Conclusion

Filtering lists is an essential React JS skill for building interactive, data-driven interfaces. JavaScript's filter() method helps select records based on conditions, while map() renders the selected records as JSX. By combining filtering with React state, controlled inputs, dropdowns, checkboxes, and API data, you can build practical features such as product searches, employee directories, student lists, and task managers.

Practise the examples and mini project to understand how filtering works with arrays, objects, state, and dynamic rendering in React.


26. React JS Training and Course Demo

Explore the following resources to learn more about React JS, list rendering, filtering, and practical application development.

Previous Next
whatsapp