React - Sort and Display Filtered List

I am looking to display only values greater than 0 on each row without removing the entire row.

I attempted filtering for black > 0, but it resulted in the removal of the entire row. I am aiming to replace 0 with an empty string.

Check out my website / code below:

https://i.sstatic.net/SYbbM.png

I would like to 'hide' or replace any 0's in this table with 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 assistance is greatly appreciated.

Edit: Would it be better to achieve this with CSS or a script?

Answer №1

Making properties display as empty strings when 0

A more efficient way to achieve this is by utilizing the map function, which allows you to uniformly apply a function to each of your properties.

const properties: (keyof Printer)[] = ["name", "serial", "black", "yellow", "magenta", "cyan", "k1", "k2", "blackPrint", "blackCopies"];
{
properties.map((property) => <td key={property}>{property != "0" ? property : ""}</td>)}

Excluding rows where all properties are 0

If you wish to hide a row that contains only zeroes for its properties, you can apply a filter before mapping the rows:

printers
.filter(printer => 
  properties.some((property) => printer[property] != "0"))
.map((printer) => {
  ...
})

This approach efficiently determines if at least one property is nonzero (indicating the printer should be shown). It is equivalent to checking if all properties are zero, but with better efficiency as .some terminates early when a condition is met.

For a more semantically clear method (though slightly less efficient), you could use:

printers
.filter(printer => 
  !properties.every(property => printer[property] == "0"))
.map((printer) => {
  ...
})

To combine both functionalities (hiding printers with all 0 properties and converting 0 properties to empty strings), the final program would look like this:

... // The rest of your component
const properties: (keyof Printer)[] = ["name", "serial", "black", "yellow", "magenta", "cyan", "k1", "k2", "blackPrint", "blackCopies"];
return (
    <>
      {printers
        ? printers
         .filter(printer => 
            properties.some(property => printer[property] != "0"))
         .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>
                {
                  properties.map((property) => <td key={property}>{property != "0" ? property : ""}</td>)
                }
              </tr>
            );
          })
        : null}
    </>
  );

Answer №2

Utilizing the ternary operator allows you to clear the column if the value is 0.

Check out this example :

            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}` != "0" ? printer.name  : "" }</td>
                <td>{`${printer.serial}` != "0" ? printer.serial  : "" }</td>
                <td>{`${printer.black}` != "0" ? printer.black  : "" }</td>
                <td>{`${printer.yellow}` != "0" ? printer.yellow  : "" }</td>
                <td>{`${printer.magenta}` != "0" ? printer.magenta  : "" }</td>
                <td>{`${printer.cyan}` != "0" ? printer.cyan  : "" }</td>
                <td>{`${printer.k1}` != "0" ? printer.k1  : "" }</td>
                <td>{`${printer.k2}` != "0" ? printer.k2  : "" }</td>
                <td>{`${printer.blackPrints}` != "0" ? printer.blackPrints  : "" }</td>
                <td>{`${printer.blackCopies}` != "0" ? printer.blackCopies  : "" }</td>
              </tr>
            );
          })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a loading spinner in a Bootstrap 5 modal while making an XMLHttpRequest

While working on a xmlhttprequest in JavaScript, I incorporated a bootstrap spinner within a modal to indicate loading. The modal toggles correctly, but I am struggling to hide it once the loading is complete. I prefer using vanilla JavaScript for this ta ...

Creating Responsive Headers Using CSS for Mobile Devices

I'm looking to make my header font size of 60px more responsive for mobile devices so that the text doesn't get cut off. Any suggestions on how to achieve this? Thank you! Here's the code snippet: h1 { font-size: 4.286em; /* 60px */ margi ...

Create a list using ReactJS

I've been working on rendering a dynamic list in JSX, but I'm facing issues displaying the items. Below is my code snippet where I attempted to use useState const [orderList, setOrderList] = useState([]) and setOrderList(prev => [...prev, chil ...

CSS fluid layout with three columns

I am attempting to create a 3-column layout where each column has a fluid width of 33% and height of 50%. However, when I add padding to the columns, it causes the last div to move to the next line. How can I resolve this issue? Example HTML: <div id= ...

Customize the appearance of a <label> tag when it is inside an <input> tag that is marked as invalid

In an ideal scenario, I wish for the text on a label to change color when the input value is considered invalid. For instance: <form> <label> Enter your name: <input type="text"> </label> </form> Ideall ...

When the submit button is clicked on a React form, it not only submits the current form

I am working on a React application with multiple forms, where each form is rendered based on the current page index. I would like the "Next" button that retrieves the next component to also act as a submit button. The issue I am facing is that while the n ...

Switching the vertical alignment of grid items in Material UI when the page is collapsed

When the page is collapsed, the Left grid item element moves to the top of the page and the Right grid element is positioned below it. I would like to reverse this behavior so that the Right element appears on top and the Left element below when the page ...

tips for displaying a label and text side by side on a single line

Is there a way to keep my label and text on the same line by adjusting the CSS? I've tried using float based on suggestions from other posts, but they still end up on different lines. .indentColumn { width: 71px; padding-top: 5%; } .labelColumn ...

Obtaining the ID from a JSON object in react.js ES6: A Comprehensive Guide

I have an array of JSON objects containing properties like Name, ID, and Address. My goal is to retrieve the IDs from all objects in this JSON array using react.js ES6. If anyone could offer guidance on how to accomplish this task, it would be greatly appr ...

Make the most of your Bootstrap 3 layout by utilizing a full page container that fills both the width and height between a fixed header and

I am currently working on a basic bootstrap page with the Example template from Bootstrap's website. I want the content in the middle to take up the space between the header and footer, while ensuring that both the header and footer remain visible at ...

MERN Application encounters UnhandledPromiseRejection Warning while attempting to save files

Currently, I am working on a project using the MERN stack. Whenever I make edits to a file and try to save them, an error pops up in the console, showing UnhandledPromiseRejection. Because of this, the changes I make to the file do not take effect. How can ...

Adjust the scroll position when the height of a div is modified

Imagine we have a large div A with a height value and below it are other divs B, C, and more. If the user is viewing divs B or C, and A reduces its height by half, the scrolling position will remain the same. However, divs B and C will move up by that amo ...

Position a component in relation to another component using AngularJS

Utilizing ng-show and ng-hide, I created a descriptive box that appears below text when clicked. However, there is an issue as the description box does not align directly under the text, similar to what is shown in this image https://i.stack.imgur.com/phBh ...

Identifying overflow of text or elements in JavaScript during execution

The website I'm working on has a unique design that requires users to scroll horizontally using the Arrow Keys instead of swiping. To achieve this, I must constantly check for overflow in text or elements each time a new page is loaded, and if necessa ...

Is it possible to have the cursor rotate or animate by 45 degrees when clicked

Do you know how to create a unique custom cursor using CSS? Say, for example, we have this code: cursor: url(images/cursor.png) 15 15, auto; Now, what if we wanted to take it up a notch and make the cursor rotate -45 degrees when clicked, and then revert ...

Tips on customizing a Drawer with Material-UI v5

When working with Material-UI v4, you could style the Drawer component like this: <Drawer variant="persistent" classes={{paper: myClassNameHere}} > The myClassNameHere is generated by using useStyles, which in turn is created using mak ...

Achieve a stylish layout by displaying three cards per row using Vue.js and Bootstrap 4

I'm facing an issue with my code where I am trying to display Bootstrap cards in rows of three, but the layout is not rendering correctly. It starts with one card, then two, and eventually adds a new column, resulting in some empty spaces with offsets ...

What is the best way to display SVGs from an API response using next/image or the <img> tag in Next.js?

I have a collection of SVGs being returned from an API response, which I am fetching inside the useEffect. The response structure is as follows: {svg1: 'https://remoteserver.com/assests/svg1.svg', ...and so on} (These SVGs are not static assets ...

What is the best way to incorporate a CSS transition without any dynamic property changes?

Is there a way to add a transition effect to a header when its size changes without a specified height value in the CSS? The header consists of only text with top and bottom padding, so as the text changes, the height adjusts accordingly. How can I impleme ...

Having trouble with your jQuery image slider?

As a newcomer to jQuery, I have been experimenting with it to gain some experience. I recently tried to integrate a jQuery image slider from slidesjs.com into my local website but unfortunately, it is not functioning as expected. Additionally, I would lik ...