Hmm, I don't see my omission, but I get a blank page with a console error saying:
Users.js:9 Uncaught TypeError: Cannot read property 'filter' of undefined
at Users.render (Users.js:9)
Apparently I'm using 'filter()' improperly. I looked around but didn't find anything 'React' related. Can Anyone help? Here are the files:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>React App</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Users from './Users';
ReactDOM.render(
<Users list={[
{ name: 'Tyler', friend: true },
{ name: 'Ryan', friend: true },
{ name: 'Michael', friend: false },
{ name: 'Mikenzie', friend: false },
{ name: 'Jessica', friend: true },
{ name: 'Dan', friend: false }
]}
/>,
document.getElementById('root')
);
Users.js
import React from 'react';
class Users extends React.Component {
render() {
return (
<div>
<h1>Friends:</h1>
<ul>
{this.props.list.friend.filter(function (friend) {
return <li>{friend[0] === 'true'}</li>
})}
</ul>
<hr />
<h1>Non Friends:</h1>
<ul>
{this.props.list.friend.filter(function (nonFriend) {
return <li>{nonFriend[0] === 'false'}</li>
})}
</ul>
</div>
);
}
}
export default Users;
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With