Shawn Matthews
Shawn Matthews

Reputation: 1832

Conditional rendering if a prop contains a blank array

I'm trying to conditionally render based on an array having values in it. So basically if this.props.data == [] don't render. If this.props.data == [{data is here}] render.

Things I've tried.

if prop exists

{this.props.data && <Field 
                    label="Data" 
                    name="data" 
                    type="select" 
                    component={SelectComponent}>
                    <option>Select data</option>
                  </Field> }

===Still Renders===

null

{this.props.data != null && <Field 
                    label="Data" 
                    name="data" 
                    type="select" 
                    component={SelectComponent}>
                    <option>Select data</option>
                  </Field> }

===Still Renders===

length

{this.props.data.length > 0 && <Field 
                    label="Data" 
                    name="data" 
                    type="select" 
                    component={SelectComponent}>
                    <option>Select data</option>
                  </Field> }

===Length is not defined===

Upvotes: 1

Views: 8263

Answers (1)

Gleb Kostyunin
Gleb Kostyunin

Reputation: 3863

You can try this:

{this.props.data && !!this.props.data.length && <Field 
                    label="Data" 
                    name="data" 
                    type="select" 
                    component={SelectComponent}>
                    <option>Select data</option>
                  </Field> }

So, check that the data is there and than check that it is not an empty array.

But I would recommend to pull it out into a method, because this way your render method can become messy really fast.

Upvotes: 9

Related Questions