In many of the frontend frameworks that I work with, there are options for ternaries or if-branches injected into the HTML logic. This is logic I use a lot. One particular case is to show when there is no data.
I just stumbled on a CSS pattern that makes my life much easier: the :only-child
pseudo-class.
React
In React, I would do "something" like this ...
{
data.length === 0
? <div>Nothing to show.</div>
: <TableWithRecords />
}
Angular
In Angular, I would do "something" like this ...
@if (data.length === 0) {
<div>Nothing to show.</div>
} @else {
<TableWithRecords />
}
Using CSS
To put it simply, I have two cases.
- There is not data.
- There is data.
<h2>No Data Showing</h2>
<ul>
<li class="handle-no-data">Nothing to show.</li>
<!-- <li>Data here</li> -->
</ul>
<h2>Data Showing</h2>
<ul>
<li class="handle-no-data">Nothing to show.</li>
<li>Data here</li>
</ul>
Using a simple CSS class .single
...
.handle-no-data:not(:only-child) {
display: none;
}
.handle-no-data:only-child {
display: flex;
}
This CSS could be simplified to ...
.handle-no-data {
&:not(:only-child) {
display: none;
}
&:only-child {
display: flex;
}
}
Here's the result of the code above ...
Summary
As you can see, I would have to move the handling of the data to the table level, but the CSS is pretty straight forward to handle a "no data" scenario.
This is exciting!
Top comments (4)
This is a great demonstration of ways to simplify logic using presentation!
I think you can eliminate the more complex
:not()
selector, though...You can also use
display: revert
to retain the element's original style.Thanks for sharing this!
I know that the :not isn’t truly necessary, but I generally prefer self-documenting code and it’s more explicit with it.
Very interesting, great use case, but also needed more explanation of only child pusedo class, although it's name also suggest it workdone, but still...
Also I think you don't need that :Not cause even if there are multiple exists it'll be hidden, and when it's only one, it'll be shown
I’ll add a link to the MDN documentation.
I like to include the :not to be explicit. I know that it operates in the cascading pattern without it. I’d rather there not be any obscurity in my code.