Filtering Lists in React
Learn how to filter arrays and display only the items that match a specific condition using filter() in React.
1. Introduction to Filtering Lists
Filtering lists means displaying only those items that satisfy a particular condition. In React, the JavaScript filter() method is commonly used to filter array data before rendering it.
For example, an application may contain a list of courses, but we may want to display only development courses. We can use filter() to select the required courses and map() to render them as JSX elements.
2. Understanding the filter() Method
The filter() method creates a new array containing only the elements for which the supplied callback returns true. The original array is not modified by filter().
Syntax
const filteredArray = array.filter((item) => {
return condition;
});
- array: The original array of items.
- item: The current item being checked.
- condition: Determines whether the item should be included.
- filteredArray: A new array containing matching items.
Simple JavaScript Example
const numbers = [10, 15, 20, 25, 30];
const filteredNumbers = numbers.filter(
(number) => number > 20
);
console.log(filteredNumbers);
Expected Output
[25, 30]
Only the numbers greater than 20 are included in the filtered array.
3. How Filtering Lists Works
The diagram shows how filter() selects matching items before map() renders them.
4. Filtering a List of Strings
Suppose we have a list of programming courses and want to display only the courses that contain the word "React".
Example
function CourseList() {
const courses = [
"React Basics",
"Angular Development",
"React Advanced",
"ASP.NET Core"
];
const filteredCourses = courses.filter(
(course) => course.includes("React")
);
return (
<div>
<h2>React Courses</h2>
<ul>
{filteredCourses.map((course) => (
<li key={course}>{course}</li>
))}
</ul>
</div>
);
}
export default CourseList;
Expected Output
React Courses
- React Basics
- React Advanced
The includes() method checks whether a string contains the specified text. Only matching course names are included in filteredCourses.
5. Filtering a List of Objects
Arrays of objects can also be filtered using object properties. For example, we can display only students who have scored at least 70 marks.
Example
function StudentList() {
const students = [
{ id: 1, name: "Amit", marks: 85 },
{ id: 2, name: "Priya", marks: 65 },
{ id: 3, name: "Rahul", marks: 78 },
{ id: 4, name: "Sneha", marks: 55 }
];
const qualifiedStudents = students.filter(
(student) => student.marks >= 70
);
return (
<div>
<h2>Qualified Students</h2>
<ul>
{qualifiedStudents.map((student) => (
<li key={student.id}>
{student.name} - {student.marks} marks
</li>
))}
</ul>
</div>
);
}
export default StudentList;
Expected Output
Qualified Students
- Amit - 85 marks
- Rahul - 78 marks
6. Combining filter() and map()
We can chain filter() and map() to filter an array and render the matching items directly.
Example
function ProductList() {
const products = [
{ id: 1, name: "Keyboard", price: 800 },
{ id: 2, name: "Mouse", price: 500 },
{ id: 3, name: "Monitor", price: 7000 },
{ id: 4, name: "Headphones", price: 1500 }
];
return (
<div>
<h2>Products Above ₹1000</h2>
<ul>
{products
.filter((product) => product.price > 1000)
.map((product) => (
<li key={product.id}>
{product.name} - ₹{product.price}
</li>
))}
</ul>
</div>
);
}
export default ProductList;
Expected Output
Products Above ₹1000
- Monitor - ₹7000
- Headphones - ₹1500
First, filter() selects products priced above ₹1000. Then, map() converts the selected products into list items.
7. Filtering with Different Conditions
The filter() method can use different conditions depending on the application's requirements.
Example: Filtering Active Employees
function EmployeeList() {
const employees = [
{ id: 1, name: "Amit", active: true },
{ id: 2, name: "Priya", active: false },
{ id: 3, name: "Rahul", active: true }
];
const activeEmployees = employees.filter(
(employee) => employee.active
);
return (
<ul>
{activeEmployees.map((employee) => (
<li key={employee.id}>{employee.name}</li>
))}
</ul>
);
}
export default EmployeeList;
Expected Output
- Amit
- Rahul
Only employees whose active property is true are displayed.
8. When No Items Match
If no items satisfy the filter condition, filter() returns an empty array. React renders no list items for an empty array.
Example
function CourseList() {
const courses = ["React", "Angular", "ASP.NET Core"];
const filteredCourses = courses.filter(
(course) => course === "Python"
);
return (
<div>
<h2>Search Results</h2>
{filteredCourses.length > 0 ? (
<ul>
{filteredCourses.map((course) => (
<li key={course}>{course}</li>
))}
</ul>
) : (
<p>No courses found.</p>
)}
</div>
);
}
export default CourseList;
Expected Output
Search Results
No courses found.
9. Common Mistakes
Mistake 1: Using map() Instead of filter()
const numbers = [10, 20, 30];
const result = numbers.map(
(number) => number > 15
);
This creates an array of Boolean values rather than selecting the matching numbers.
Correct Code
const result = numbers.filter(
(number) => number > 15
);
// Result: [20, 30]
Mistake 2: Forgetting the Return Value
const result = numbers.filter((number) => {
number > 15;
});
When using curly braces in the callback body, return the condition explicitly. Otherwise, the callback returns undefined.
Correct Code
const result = numbers.filter((number) => {
return number > 15;
});
10. Practice Tasks
Complete these tasks to practise filtering lists in React.
Summary
The filter() method creates a new array containing only the items that satisfy a specified condition. In React, it can be used to filter arrays of strings, numbers, or objects before rendering them. Combining filter() with map() makes it easy to select matching data and display the corresponding JSX elements. When no items match, the filtered array is empty, so conditional rendering can be used to display a helpful message.