Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Text strings must be rendered within a <Text> component with if condition

*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.stack.imgur.com/UkHS6.png

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading