Tell us what’s happening:
I am getting this error message below and can’t figure out how to fix it. I believe that I am writing the filter and map methods correctly. I believe that I using the key in each li correctly. Any ideas appreciated!!!
// running test
Method “key” is only meant to be run on a single node. 0 found instead.
MyComponent should render li elements that contain the username of each online user.
MyComponent should return a div, an h1, and then an unordered list containing li elements for every user whose online status is set to true.
// tests completed
It is not required to place in the outer curly braces that surround the list tags, nor is it needed to convert the values to strings. Correct those first, and mind you the variable item is a object, you want to pull something from it to represent the key.
Thank you for your reply! I added an index element in map and used that as the key. I am still getting an error that says ‘Objects are not valid as a React child (found: object with keys {username, online}).’ Don’t really understand what this error means but below is my code. Appreciate your feedback!
Thank you for your reply! I added an index element in map and used that as the key. I am still getting an error that says ‘Objects are not valid as a React child (found: object with keys {username, online}).’ Don’t really understand what this error means but below is my code. Appreciate your feedback!
Hello! Thank you for your reply! So I made the change per your suggestion but I am still getting an error
Objects are not valid as a React child (found: object with keys {username, online}). Any ideas appreciated!
In the above code, remember that “item” represents an object, in this case a “user.” Each “user” object has two properties associated with it, a ‘username’ property and an ‘online’ property (online status). What we want to display is the username of the user, which would be, in this case, item.username
render() {
let usersOnline = this.state.users.filter(user => {
return user.online === true; /* can use just - (return user.online),
put for your reference. */
}) ;
/* filters through the Array - 'users' which is present in the
'state' and returns only those users which has 'online' property with
value of 'true' in a new Array called 'usersOnline'*/
let renderOnline = usersOnline.map((Un,i) => {
return <li key={i}> {Un.username} </li>
});
/* Now, the new Array 'usersOnline' is mapped through to get the
'username' values present in it, and return a <li> element containing
the 'usernames' and a unique 'key' value (here its the index value)
which is passed in to a new Array called 'renderOnline' containing
the above mentioned values */
return (
<div>
<h1>Current Online Users:</h1>
<ul>
{renderOnline}
</ul>
</div>
);
}
};