bier hier
bier hier

Reputation: 22520

How can I check condition in reactjsx?

Just started looking at reactjsx and trying to check whether an array (this.state.content) is not undefined and length > 0. This is part of the render method:

 display = (
        <section>
            {
               if (this.state.content.length >0)
               {
                this.state.content.map((item, i) => {
                    return <CardRenderer addPacks={true} key={i} container={item}/>
                })
              }
            }
        </section>
    )

This does not work however , how can I check this arraylength first in jsx?

Upvotes: 1

Views: 64

Answers (2)

Shubham Khatri
Shubham Khatri

Reputation: 281646

You can make use of ternary operator

display = (
        <section>
            {
               (this.state.content && this.state.content.length > 0)?
               {
                this.state.content.map((item, i) => {
                    return <CardRenderer addPacks={true} key={i} container={item}/>
                })
              } : null
            }
        </section>
    )

Upvotes: 0

Shane
Shane

Reputation: 196

Try:

 display = (
        <section>
               {
                this.state.content && this.state.content.map((item, i) => {
                    return <CardRenderer addPacks={true} key={i} container={item}/>
                })
            }
        </section>
    )

The && will short circuit the map if this.state.content is undefined, and if this.state.content has a length of zero, map will do nothing (but there will not be an error).

Upvotes: 1

Related Questions