I need to display an empty state when my list is empty.
That should be easy, how do you plan on achieving that?
Thought about several methods:
- Class toggling
<div>
<ul className={list.length > 0 ? 'show' : 'hide'}>...</ul>
<div className={list.length > 0 ? 'hide' : 'show'}>...empty content...</div>
</div>
- Conditional rendering
list.length > 0 ? <Somecomponent /> : <EmptyView />
Hmm, they do work, but I think there's a simpler way to get that done.
Really? how
So CSS has an :empty
selector which matches elements with no children - (check here).
<div>
<ul className='list'>
{list.map(item => <li>{item}</li>)}
</ul>
<div className='empty-view'>
<p>List is empty</p>
</div>
</div
CSS
.empty-view {
display: none;
}
.list:empty ~ .empty-view {
display: block;
}
Result
Pros
- Works without JavaScript
- Nothing has to change if you decide to use a framework
Cons
Empty
element is always present in the DOM.
Cover image by Data vector created by stories - www.freepik.com