Reputation: 173
I have a couple of objects for environments (envList
) and teams (teamsList
) like so:
const envList = {
dev: "DEV",
sit: "SIT",
uat: "UAT",
qa: "QA",
prod: "PROD"
};
const teamsList = {
a: "Team A",
b: "Team B",
c: "Team C",
d: "Team D"
};
I am looping over them to show them like (sort of) a table:
<div className="App">
{Object.keys(teamsList).map((key, i) => (
<div className="team" key={i}>
<span className="teamname">{teamsList[key]}</span>
{Object.keys(envList).map((key, i) => (
<span className="env-th-cell" key={key}>
{envList[key]}
</span>
))}
</div>
))}
</div>
Note: The above is JSX, but it is not really a React problem. Just nesting maps over teams and environments.
Generating an output such as
Team A DEV SIT UAT QA PROD
Team B DEV SIT UAT QA PROD
Team C DEV SIT UAT QA PROD
Team D DEV SIT UAT QA PROD
I need to add a CSS class (.red
) to highlight the env for any team based on the following redTeams
array:
const redTeams = [
{
envIndex: 0,
team: "Team A"
},
{
envIndex: 0,
team: "Team B"
},
{
envIndex: 4,
team: "Team B"
}
{
envIndex: 3,
team: "Team C"
},
{
envIndex: 4,
team: "Team C"
}
];
if a team
and an envIndex
is present in redTeams
, I want to add a class on the span for that environment. There could be more than one entries for a team in redTeams.
Team A DEV(red) SIT UAT QA PROD
Team B DEV(red) SIT UAT QA PROD (red)
Team C DEV SIT UAT QA(red) PROD
Team D DEV SIT UAT QA PROD(red)
The above output is for representation, there is no (red), but a class added to the span
Here is a sandbox https://codesandbox.io/s/pwjxy82j5x?fontsize=14
Some advice on the approach would be helpful and appreciated
Upvotes: 1
Views: 905
Reputation: 281626
You need to conditionally add className while rendering. Before that you need to create a map for envIndex to env mapping
<div className="App">
{Object.keys(teamsList).map((key, i) => {
const teams = redTeams.filter(team => teamsList[key] === team.team);
return (
<div className="team" key={i}>
<span className="teamname">{teamsList[key]}</span>
{Object.keys(envList).map((key, i) => {
let className = "env-th-cell";
if (
teams &&
teams.findIndex(
t => envList[key] === indexToEnvMap[t.envIndex]
) > -1
) {
className += " red";
}
return (
<span className={className} key={key}>
{envList[key]}
</span>
);
})}
</div>
);
})}
</div>
Upvotes: 2