React: how to use the JavaScript filter() method

React: how to use the JavaScript filter() method

The filter() method in JavaScript is a powerful tool when working with arrays, and is particularly useful in combination with React to manipulate and filter the data displayed in the user interface.

The filter() method in JavaScript is a powerful tool when working with arrays, and is particularly useful in combination with React to manipulate and filter the data displayed in the user interface.

In React, you can use the filter() method to create a filtered copy of an array of elements. For example, if you have an array of objects representing users and want to display only active users, you can use filter() to filter the array based on a specific criteria.

Here is an example of using filter() in React:


import React, { useState } from 'react';

function UserList() {
  const [users, setUsers] = useState([
    { id: 1, name: 'Mario', active: true },
    { id: 2, name: 'Luigi', active: false },
    { id: 3, name: 'Peach', active: true },
    { id: 4, name: 'Toad', active: false }
  ]);

  const activeUsers = users.filter(user => user.active);

  return (
    <div>
      <h1>Lista Utenti Attivi</h1>
      <ul>
        {activeUsers.map(user => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default UserList;

In the example above, the users array contains a list of users with properties like id, name and active. The filter() method is used to get a fresh copy of the array that includes only active users. This filtered array is then mapped inside a <ul> element to view the names of active users in the list.

The filter() method offers considerable flexibility, as it allows you to define custom filter criteria to fit specific application needs. You can filter on different object properties or apply more complex logic. Using filter() in combination with React allows for easy handling the data and to render the user interface according to specific criteria.