I want to only show values greater than 0 on each row.
I tried filtering for black > 0 etc but it removed the whole row, whereas i just want to make a 0 into an empty string essentially.
Here is my website / code:
Any of the 0’s in this table i would like to ‘hide’ or make them an empty string.
import axios from "axios";
import { useEffect, useState } from "react";
const PRINTER_REST_API_URL = "http://localhost:8080/GetReport";
export type Printer = {
address: string;
black: number;
blackCopies: number;
blackPrints: number;
colourCopies: number;
colourPrints: number;
cyan: number;
k1: number;
k2: number;
location: string;
magenta: number;
name: string;
serial: string;
yellow: number;
};
export function GetPrinters() {
const [printers, setPrinters] = useState<Printer[] | null>();
useEffect(() => {
axios.get(PRINTER_REST_API_URL).then((response) => {
setPrinters(response.data);
});
}, []);
return (
<>
{printers
? printers.map((printer) => {
return (
<tr key={printer.address}>
<td>{printer.location}</td>
<td>
<a
href={"//" + printer.address}
target="_blank"
rel="noopener noreferrer"
>
{printer.address}
</a>
</td>
<td>{printer.name}</td>
<td>{printer.serial}</td>
<td>{printer.black}</td>
<td>{printer.yellow}</td>
<td>{printer.magenta}</td>
<td>{printer.cyan}</td>
<td>{printer.k1}</td>
<td>{printer.k2}</td>
<td>{printer.blackPrints}</td>
<td>{printer.blackCopies}</td>
</tr>
);
})
: null}
</>
);
}
Any help is appreciated.
Edit: Is this perhaps better achieved with CSS or a script?
2
Answers
You can use the ternary operator to make the column empty if the value is 0.
Here is an example :
Filtering individual properties to show as empty strings if they are 0
A more concise way to write this would be using
map
which allows you to apply the same function to each of your properties.Removing rows where all properties are 0
If you wanted to hide a row, which had all zeroes for its property you could add a filter before mapping to rows:
This is an efficient way of testing if at least one of your properties is nonzero (in this case you would want to show the printer). This is equivalent to testing if all of the entries are zero, but more efficient as .some exits early the first time a condition is matched.
If you wanted a more semantic way to do this (but slightly less efficient) you could write:
If you wanted both of these features (removing printers which have all 0 properties and filtering 0 properties to be empty strings) the resulting program would look like this: