Neha
Neha

Reputation: 95

How to find if element exists in an array in react-native

I am trying to render an element after checking whether there is a string e.g. "abc" present in an array. I have tried using various different functions like array.find(), array.includes(), array.some() While I do so, it gives me an error -

TypeError: null is not an object(evaluating 'o.includes')

Below is the piece of code that I am using inside render function. "abc" is the array where I am trying to check whether string "a" exists in that array, if it does then display that ExpandedHeader element.

PS: I am new to react-native.

<View>
{abc.includes("a") && <ExpandedHeader title={"Got it"} 
       expanded={this.state.riskRatingExpanded}
       onPress={() => {this.setState({
                    riskRatingExpanded :!this.state.riskRatingExpanded,
                    basicDetailsExpanded : false,
                    envProfileExpanded : false,
                    nwswProfileExpanded : false,
                    additionalInfoExpanded : false,
                    scoresExpanded : false,
                  });
             }}

         />}
</View>

But instead, if I do the below it works -

<View>
    {abc != null && <ExpandedHeader title={abc[0]} 
           expanded={this.state.riskRatingExpanded}
           onPress={() => {this.setState({
                        riskRatingExpanded :!this.state.riskRatingExpanded,
                        basicDetailsExpanded : false,
                        envProfileExpanded : false,
                        nwswProfileExpanded : false,
                        additionalInfoExpanded : false,
                        scoresExpanded : false,
                      });
                 }}

             />}
    </View>

Upvotes: 0

Views: 1960

Answers (1)

Sarmad Shah
Sarmad Shah

Reputation: 3805

Your render function runs before your array data is present and initially your array data is null,

make sure you initialise your abc state as array first,

state = { abc: [] }

with this, your first code should work.

Upvotes: 1

Related Questions