avatarThiago Bernardes

Summary

The article presents a CSS-based method to display "No items found" in dynamic lists, which is applicable across various frameworks like Angular, React, and Vue.

Abstract

The article discusses a common challenge faced by front-end developers when dealing with dynamic lists in HTML: displaying a "No items found" message when the list is empty. Traditional solutions involve using IF/ELSE statements or framework-specific constructs like Angular's *ngIf directive, often in conjunction with pipes or filters, or functions to filter the list. The author proposes a simpler, framework-agnostic approach using CSS. By adding a .no-item class to the last item in the list and utilizing the :not(:first-child) selector, the message will only display when the list is empty. This method requires the list to be wrapped in a tag with all items as siblings, typically achieved with ul and li tags. A working example is provided via an embedded CodePen.

Opinions

  • The author suggests that the CSS method is more efficient than the traditional IF/ELSE approach.
  • The CSS solution is versatile and can be applied to any

A smart way to display “No items found” on a list

Photo by Pankaj Patel on Unsplash

It’s often front-end developers use IF/ELSE to display “No Items found” when using dynamic lists on HTML.

This solution works for every framework (Angular, React, Vue, …) as it’s based on CSS.

Giving an angular example below:

  • {{item}}
  • No item
or even

Sometimes the example above uses pipe/filters:

  • Or maybe functions:

  • To solve this problem, you can simply use CSS, and it will work in any situation:

    .no-item:not(:first-child) { display:none; }

    Add this class to the last item on your list, and it will just work! Note: that the list has to be wrapped by any tag, and in that wrap, and all the items as siblings and wrapped by the same tag (commonly used with ul and li)

    Find a working example below:

    JavaScript
    Angular
    React
    Vue
    CSS
    Recommended from ReadMedium