Mahmud Adam Mahmud Adam - 1 year ago 47
React JSX Question

How to prevent empty item in list from being displayed?

I am mapping over an array of books and displaying the titles in an

ul
list, but the problem is that, since I have a default value for title set as an empty string, the list renders that initial empty
li
item. Here is my book array:

@observable books = [
{title:"", owned: false}
]


And I am displaying the books like so:

<div>
{this.props.store.books.map((b)=>{
return (
<ul>
<li>{b.title}</li>
</ul>
)
})}
</div>


How do I prevent the empty title from being displayed?

Answer Source

If you don't care about displaying the whole thing if the title is empty, you could use .filter() on the array, e.g.

<div>
    {this.props.store.books.filter(x => x.title).map((b) => {
        return (
            <ul>
                <li>{b.title}</li>
            </ul>
        )
    })}
</div>

If you want to explicitly exclude the title only and still display other things you could consider turning it's <li> in to a variable that you render. e.g.

  <div>
        {this.props.store.books.map((b)=>{
            const title = b.title ? <li>{b.title}</li> : null;
            return (
                <ul>
                    {title}
                </ul>
            )
        })}
  </div>