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

Time:02-17

*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

CodePudding user response:

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>

CodePudding user response:

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

  • Related