Array.filter() to Dynamically Filter an Array

Array.filter() to Dynamically Filter an Array
0

#1

Does anybody have any idea why this code does not work? It should first filter the state object of any users who are not online, then map a new array listing the names of the online users when the component is placed. But no avail - and I don’t understand why.

Your code so far


class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      users: [
        {
          username: 'Jeff',
          online: true
        },
        {
          username: 'Alan',
          online: false
        },
        {
          username: 'Mary',
          online: true
        },
        {
          username: 'Jim',
          online: false
        },
        {
          username: 'Sara',
          online: true
        },
        {
          username: 'Laura',
          online: true
        }
      ]
    }
  }
  render() {
    const usersOnline = this.state.users.filter(x => x.online
    ); // change code here
    const renderOnline = usersOnline.map((user) => <li key = {user.username.toString()} > {user.username} </li>); // change code here
    return (
       <div>
         <h1>Current Online Users:</h1>
         <ul>
           {renderOnline}
         </ul>
       </div>
    );
  }
};

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/front-end-libraries/react/use-array-filter-to-dynamically-filter-an-array


#2

In your filter() call, you probably meant user => user.online (with no braces)

You also can’t put an object between the braces in JSX, like you did with <li>{user}</li>


#3

Your code is correct. However, there is one tiny formatting error.

<li key = {user.username.toString()} > {user.username} </li>

The space must be trimmed. Remember HTML still preserves one level of space.


#4

The test is not expecting you to have a space before and after the username in each li element.


#5

Yeah, that did the trick! Thanks!