1

*I am a new for react native and JavaScript . This not a advance quection.I just try to compare a string like in java .but it doesn't work .when run this it also print the if conditions like a sting .

 <FlatList 
        data={data}
        keyExtractor={({id },index) => id}
        renderItem={({item}) =>(

          <View style={styles.container}>

            if({item.id} ==1){
              <Text style={styles.textStyle1}>ID is : {item.id}</Text>
            }else{
              <Text >ID is : {item.id}</Text>
            }
               
                <Text style={styles.textStyle2}>Title is :{item.title}</Text>
                <Text style={styles.textStyle3}>releaseYear is :  {item.releaseYear}</Text>
          </View>
          
          
        )}
      
      />   

 
    
    
    * error
    Error: Text strings must be rendered within a <Text> component.
    
    
    * output in web
    
    [![enter image description here][1]][1]
    
    
      [1]: https://i.sstatic.net/UkHS6.png
0

2 Answers 2

2

You cannot add code inside JSX elements but you can do the following:

Add the code inside a block and use Conditional (ternary) operator:

  <View style={styles.container}>

    {
    item.id ==1 ?
      <Text style={styles.textStyle1}>ID is : {item.id}</Text>
    :
      <Text >ID is : {item.id}</Text>
    }
       
        <Text style={styles.textStyle2}>Title is :{item.title}</Text>
        <Text style={styles.textStyle3}>releaseYear is :  {item.releaseYear}</Text>
  </View>

Or you may use Immediately Invoked Function Expressions (IIFEs)

   {(function() {
      if (item.id==1) {
        return <Text style={styles.textStyle1}>ID is : {item.id}</Text>;
      } else {
        return <Text >ID is : {item.id}</Text>
      }
    })()}
   
    <Text style={styles.textStyle2}>Title is :{item.title}</Text>
    <Text style={styles.textStyle3}>releaseYear is :  {item.releaseYear}</Text>
Sign up to request clarification or add additional context in comments.

5 Comments

it's work . but i have add {} and try to use if condition it doesn't work
I will add one more method that will help with your case
Immediately Invoked Function Expressions not work for me
Can you explain how it doesnt work ? error or what?
I make another condition with immediate invoked and I check it(item.title =='Inception') but it didn't return true and false. i think it doesn't read
1

Try this :

{item.id ==1 ? <Text style={styles.textStyle1}>ID is : {item.id}</Text>
     : <Text >ID is : {item.id}</Text>
}

Have a look at Conditional Rendering

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.