Filtering A List With React Filtering A List With React reactjs reactjs

Filtering A List With React


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;


You are calling .friend on the list itself when that's a property of each object in your array. You are also using .filter, but I don't think you're using it correctly here. .filter will return an array with certain elements where the function passed in returns a truthy value. Here's how you could do it with .filter:

var nonFriends = this.props.list.filter(function (user) {  return !user.friend;});var friends = this.props.list.filter(function (user) {  return user.friend;});return (  <div>    <h1>Friends:</h1>    <ul>{ friends }</ul>    <h1>Non Friends:</h1>    <ul>{ nonFriends }</ul>  </div>);

You could also do a .forEach for 1 pass through the array if the array is large:

var nonFriends = [], friends = [];this.props.list.forEach(function (user) {  if (user.friend) {    friends.push(user);  } else {    nonFriends.push(user);  }});// now render friends and nonFriends


I think that you are trying to filter the atribute, and not the list. Try to change this:

this.props.list.friend.filter

to this:

this.props.list.filter