How to apply filter in list using react

Asked
Active3 hr before
Viewed126 times

10 Answers

usingapplyfilterreact
90%

Finally, we perform another function after the filter function: the map function. This is how we can output the array elements that match the filter condition to the actual user interface inside of li tags.if(typeof __ez_fad_position != 'undefined'){__ez_fad_position('div-gpt-ad-upmostly_com-banner-1-0')};,Because we are performing a function we open up a set of parentheses. This is where we want to set our condition for the filter: in this case, if the element in the array includes the letter ‘J’.,To do that, we use the filter function. We can perform the filter function inside of our JSX in a React component like so:

const names = ['James', 'John', 'Paul', 'Ringo', 'George'];
load more v
88%

Okay, looks like "Users.js" should be:, Users ,Theoretical Computer Science

Okay, looks like "Users.js" should be:

import React from 'react';

class Users extends React.Component {
  render() {
    let friends = this.props.list.filter( function (user) {
      return user.friend === true
    });

    let nonFriends = this.props.list.filter( function (user) {
      return user.friend !== true
    });

    return (
      <div>
        <h1>Friends:</h1>
        <ul>
          {friends.map(function (user) {
            return <li key={user.name}>{user.name}</li>
          })}
        </ul>
        <h1>Non Friends:</h1>
        <ul>
          {nonFriends.map(function (user) {
            return <li key={user.name}>{user.name}</li>
          })}
        </ul>
      </div>
    );
  }
}

export default Users;

Or even this:

import React from 'react';

class Users extends React.Component {
  render() {
    return (
      <div>
        <h1>Friends:</h1>
        <ul>
          {this.props.list.filter(function (user) { // filter first for friends
            return user.friend === true // returns a new array
          }).map(function (user) {  // map the new array to list items
            return <li key={user.name}>{user.name}</li> // don't forget unique key for each item
          })}
        </ul>

        <hr />

        <h1>Non Friends:</h1>
        <ul>
          {this.props.list.filter(function (user) { // filter first for non-friends
            return user.friend !== true // returns a new array
          }).map(function (user) {  //map the new array to list items
            return <li key={user.name}>{user.name}</li> // don't forget unique key for each item
          })}
        </ul>
      </div>
    );
  }
}

export default Users;
load more v
72%

Conditional rendering,Editing the name of a task,Vue conditional rendering: editing existing todos

function editTask(id, newName) {
   const editedTaskList = tasks.map(task => {
      // if this task has the same ID as the edited task
      if (id === task.id) {
         //
         return {
            ...task,
            name: newName
         }
      }
      return task;
   });
   setTasks(editedTaskList);
}
load more v
65%

You can chain the filter() and map() function together to shorten your code like this:,The filter() function accepts a callback function and use it to test the value of each element. It will then return an array with the elements that pass the test. If no elements pass the test, an empty array will be returned. You can then use the map() function to render the new array.if(typeof __ez_fad_position!='undefined'){__ez_fad_position('div-gpt-ad-sebhastian_com-box-4-0')};,The result will be the same. You can use the filter with any type of data.

function App(){
  const array = [ 23, 45, 67, 89, 12 ]
  const largerThanSixty = array.filter( number => {
    return number > 60
  })

  return (
    <ul> Number greater than 60:
      { largerThanSixty.map(number => <li>{number}</li>) }
    </ul>
  )
}
load more v
75%

The ExamplePreviewJavascript codeCSS code,This article walks you through a complete example of making a filter (searchable) list in React. We’ll use the most recent version of React (17.0.2) as well as use functional components and hooks. ,React useReducer hook – Tutorial and Examples

Here’s the full souce code in src/App.js:

import React, { useState } from 'react';

import './App.css';

// This holds a list of some fiction people
// Some  have the same name but different age and id
const USERS = [
  { id: 1, name: 'Andy', age: 32 },
  { id: 2, name: 'Bob', age: 30 },
  { id: 3, name: 'Tom Hulk', age: 40 },
  { id: 4, name: 'Tom Hank', age: 50 },
  { id: 5, name: 'Audra', age: 30 },
  { id: 6, name: 'Anna', age: 68 },
  { id: 7, name: 'Tom', age: 34 },
  { id: 8, name: 'Tom Riddle', age: 28 },
  { id: 9, name: 'Bolo', age: 23 },
];

function App() {
  const [name, setName] = useState('');
  const [foundUsers, setFoundUsers] = useState(USERS);

  const filter = (e) => {
    const keyword = e.target.value;

    if (keyword !== '') {
      const results = USERS.filter((user) => {
        return user.name.toLowerCase().startsWith(keyword.toLowerCase());
        // Use the toLowerCase() method to make it case-insensitive
      });
      setFoundUsers(results);
    } else {
      setFoundUsers(USERS);
      // If the text field is empty, show all users
    }

    setName(keyword);
  };

  return (
    <div className="container">
      <input
        type="search"
        value={name}
        onChange={filter}
        className="input"
        placeholder="Filter"
      />

      <div className="user-list">
        {foundUsers && foundUsers.length > 0 ? (
          foundUsers.map((user) => (
            <li key={user.id} className="user">
              <span className="user-id">{user.id}</span>
              <span className="user-name">{user.name}</span>
              <span className="user-age">{user.age} year old</span>
            </li>
          ))
        ) : (
          <h1>No results found!</h1>
        )}
      </div>
    </div>
  );
}

export default App;
load more v
40%

To create the example project for this example, open command prompt, navigate to a convenient location, and run the command as shown below :

To create the example project for this example, open command prompt, navigate to a convenient location, and run the command as shown below :

create - react - app example11
load more v
22%

If you’re using Visual Studio Code, you can use Ctrl+` (Control backtick) to bring up an integrated terminal. Either way, run npm start from a terminal. You should see an empty page because we just removed everything from it., Using Visual Studio Code with Unity3D on Linux ,Using Visual Studio Code with Unity3D on Linux - Gigi Labs on Getting Started with Unity3D on Linux

import React from 'react';
import './App.css';

function App() {
  return (
    <div className="App">

    </div>
  );
}

export default App;
load more v
60%

Pretag
 Pretag team - issue, fix, solve, resolve
48%

In this article I am going to show you from scratch how to implement a searchable/filtered list of data in React.,Our final task is to implement the search/filter functionality on this list of data.,We will then pass in data as an argument to the callback function of filter that represents each item in the array.

The first thing we need to do is create a react project. To do this create a folder on your desktop which will contain the project. In addition, navigate to this folder in a terminal and then enter the below command.

npx create - react - app reactsearchable
load more v
23%

From line 27 we display an error message if getting data from our API fails. If it doesn't fail we display the data as a list. ,Then we want to display our received data as a list of Countries. The final code to do this looks like this:,Basically we will fetch the data from our API endpoint https://restcountries.eu/rest/v2/all and display the data in a user readable form.

Pretag
 Pretag team - issue, fix, solve, resolve

Other "using-apply" queries related to "How to apply filter in list using react"