Skip to content
Advertisement

React map how to remove empty elements?

I have objects, some of these objects have different properties when the map renders empty elements for me https://ibb.co/BGnB0xL How can I remove these empty elements? maybe you need to use filter or something else?

JavaScript_Lessons_Objects.js

JavaScript

Lesson.jsx

JavaScript

I think the problem is clear when I added to the heading object: [<div> <span className = {jsStyle.title}> JSON OBJECTS </span> </div>], I got empty paragraphs. I specially set the color orange to make it easier to navigate, besides, I added some code at the end. Please pay attention to this { !!item.title && <li>more code here</li>} and here is the result https://ibb.co/JRKY2dx I need to get rid of Blank paragraphs

Advertisement

Answer

If you are simply trying to conditionally render the list item with the item title you don’t have to use a ternary.

Inline If with Logical && Operator

JavaScript

And since it seems that titleName also conditionally renders a list item

JavaScript

To also remove a bit of DOM noise (and not inject empty divs on the off-hand case that no list items are rendered), I also suggest returning the list items (li) in a React Fragment.

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement