I have an array of dictionaries. Each dict represents a row in the table that should be appearing on the UI. Each row should respect one of two conditions. Based on these conditions the background color of that row should be in one two options. My solution was to analyze the state and divide it into different arrays. Then I map the two arrays (one after the other) with different background colors. I didn't like this option because it is basically repeating the same code. It will also prohibit me from implementing an overall research functionality in a next step. Can anyone propose a map function that takes the overall state and return each row with respect to background color given to it?
const TsdzList = (props) => {
// all dicts to map
const [testPackagesList, setTestPackagesList] = useState([]);
// rows that respect cdt1
const [newTestPackages, setNewTestPackages] = useState([]);
// rows that respect cdt2
const [oldTestPackages, setOldTestPackages] = useState([]);
const getNewTestPackages = () => {
let tsdzNewTestPackageNames = [];
let tsdzOldTestPackageNames = [];
for (const dict of testPackagesList) {
if (condition1) {
tsdzNewTestPackageNames.push(dict);
}
if (condition2) {
tsdzOldTestPackageNames.push(dict);
}
}
setNewTestPackages(tsdzNewTestPackageNames);
setOldTestPackages(tsdzOldTestPackageNames);
};
return (
<Table size="small">
<TableHead>
<TableRow>
<TableCell>ID</TableCell>
<TableCell>data</TableCell>
</TableRow>
</TableHead>
<TableBody>
{newTestPackages.map((report, index) => (
<TableRow>
<TableCell required>{report.id}</TableCell>
<TableCell>{report.data}</TableCell>
</TableRow>
))}
{oldTestPackages.map((report, index) => (
<TableRow key={index}>
<TableCell required>{report.id}</TableCell>
<TableCell>{report.data}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
<Button
sx={{ m: 2 }}
onClick={() => {
getNewTestPackages();
}}
variant="contained"
>
Show
</Button>
);
};
From the code one can notice that the only difference between the two mapped functions is the background color. Is it possible to use only one map function that looks something like this {testPackagesList.map((report, index) => (
and get rid of that button Show? instead of that button, the analysis can be begin as soon as the testPackagesList is filled.