user2026178
user2026178

Reputation: 318

React Native - Trying to print depending on the state of index

I am trying to loop through this array and print out the quote, depending on if it is saved as true or false. At the moment, it just prints out in the JSON array. I'm new to react native, so not 100% certain of the behaviour of map.

var savedQuote = quotes.quotesArray.map(quote => quote.isSaved) 

{
                  quotes.quotesArray.map((quote, i) => {
                    if(savedQuote){
                        return(                            
                            <TouchableOpacity key={i} style = {styles.border}>
                              <Text style = {styles.text}>
                                i: {i}. {quotes.quotesArray[i].preview}
                              </Text>
                            </TouchableOpacity> 
                        )
                    }
                    else{
                        return <Text key = {i}>{i}Nada</Text>
                    }
                  })
                }

Upvotes: 0

Views: 112

Answers (1)

Kevin Amiranoff
Kevin Amiranoff

Reputation: 14543

I don't understand why you have two map in your code. One should suffice :

quotes.quotesArray.map((quote, i) => {
  if(quote.isSaved){
    return(                            
      <TouchableOpacity key={i} style = {styles.border}>
        <Text style = {styles.text}>
          i: {i}. {quote.preview}
        </Text>
      </TouchableOpacity> 
    )
  } else {
    return <Text key = {i}>{i}Nada</Text>
  }
});

This will loop through quotes and either return one node or the either if quote.isSaved is true or not.

you could save them to a new array if you assign it to a new variable ex: var savedQuotes = ... or use it inside your render function :

   render() {
     return (
       <View>
        {quotes.quotesArray.map...}
      </View>
     );
   }

The map() method creates a new array with the results of calling a provided function on every element in this array.

Here is more information: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Here are some examples from the react documentation : https://facebook.github.io/react/docs/lists-and-keys.html (which should be close enough to react-native)

Upvotes: 1

Related Questions