Middle
Implement a component to display a list of teams with members. Given an array of teams (with name and list of user IDs) and a separate array of users (with ID and name), match teams with users by user ID and display team cards with member listings. If no members, show 'no members'; if user ID exists but user not found, show a dash. User ID may come as an array, number, null, or undefined.
sobes.tech AI
Answer from AI
Below is an example implementation of a React component that takes an array of teams and users, matches participants by ID, and displays participant cards:
import React from 'react';
function TeamList({ teams, users }) {
// Create a user map by ID for quick lookup
const userMap = React.useMemo(() => {
const map = new Map();
users.forEach(user => {
map.set(user.id, user.name);
});
return map;
}, [users]);
// Function to get list of participant names
const getParticipantNames = (userIds) => {
if (!userIds) return ['no participants'];
// Convert userIds to array
let ids = [];
if (Array.isArray(userIds)) {
ids = userIds;
} else if (typeof userIds === 'number') {
ids = [userIds];
} else {
return ['no participants'];
}
if (ids.length === 0) return ['no participants'];
return ids.map(id => {
if (id === null || id === undefined) return '-';
return userMap.has(id) ? userMap.get(id) : '-';
});
};
return (
<div>
{teams.map(team => (
<div key={team.name} style={{border: '1px solid #ccc', margin: '10px', padding: '10px'}}>
<h3>{team.name}</h3>
<ul>
{getParticipantNames(team.userIds).map((name, idx) => (
<li key={idx}>{name}</li>
))}
</ul>
</div>
))}
</div>
);
}
export default TeamList;
Explanation:
- Create a user map for quick name lookup by ID.
- Handle
userIds, considering it can be an array, number, null, or undefined. - If there are no participants, display "no participants".
- If IDs exist but the user is not in the list, display "-".
- Render team cards with a list of participants.