Mahmud Adam
Mahmud Adam

Reputation: 3579

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?

Upvotes: 1

Views: 1666

Answers (2)

Suneesh Patteri
Suneesh Patteri

Reputation: 25

You can hide empty list simply by using css3 style

CSS

ul li:empty {
   display: none;
}

Upvotes: 1

JVDL
JVDL

Reputation: 1202

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>

Upvotes: 2

Related Questions