Reputation: 489
I have a table that is usng a sample dataset to populate. I want to set the cell color based on what value is in the the cell. I am not really too sure how to do that at this point.
The CSS I want to use is here:
.background-green {
background-color: #009000;
color: #ffffff;
}
.background-red {
background-color: #ff0000;
color: #ffffff;
}
The sample data I am using is here:
export const dataset = [
{ sampleid: "1", sample1: "No", sample2: "Yes", sample3: "No", sample4: "Yes",
sample5: "Yes" },
{ sampleid: "2", sample1: "No", sample2: "Yes", sample3: "No", sample4: "Yes",
sample5: "Yes" }
The function used to populate the table is here:
export function myTabledata() {
return dataset.map(data=> (
<tr>
<td>{data.sampleid}</td>
<td>{data.sample1}</td>
<td className={'background-red'}>{data.sample2}</td>
<td>{data.sample3}</td>
<td>{data.sample4}</td>
<td>{data.sample5}</td>
</tr>
)
);
}
I did set one tag to use the red CSS it does apply it however I am trying to understand to do it conditionally
Upvotes: 0
Views: 62
Reputation: 10520
You can use a ternary operator like this:
<td className={data.sample2 === 'Yes' ? 'background-green' : 'background-red'}>{data.sample2}</td>
If the condition is truthy (data.sample2 === Yes
) background-green
class will apply, otherwise (data.sample2 === No
) background-red
will apply.
Upvotes: 3