if-else statement inside jsx: ReactJS

You can achieve what you are saying by using Immediately Invoked Function Expression (IIFE)

render() {
    return (   
        <View style={styles.container}>
            {(() => {
              if (this.state == 'news'){
                  return (
                      <Text>data</Text>
                  )
              }
              
              return null;
            })()}
        </View>
    )
}

Here is the working example:

Edit awesome-yalow-eb2nu

But, In your case, you can stick with the ternary operator


As per DOC:

if-else statements don't work inside JSX. This is because JSX is just syntactic sugar for function calls and object construction.

Basic Rule:

JSX is fundamentally syntactic sugar. After compilation, JSX expressions become regular JavaScript function calls and evaluate to JavaScript objects. We can embed any JavaScript expression in JSX by wrapping it in curly braces.

But only expressions not statements, means directly we can not put any statement (if-else/switch/for) inside JSX.


If you want to render the element conditionally then use ternary operator, like this:

render() {
    return (   
        <View style={styles.container}>
            {this.state.value == 'news'? <Text>data</Text>: null }
        </View>
    )
}

Another option is, call a function from jsx and put all the if-else logic inside that, like this:

renderElement(){
   if(this.state.value == 'news')
      return <Text>data</Text>;
   return null;
}

render() {
    return (   
        <View style={styles.container}>
            { this.renderElement() }
        </View>
    )
}

I find this way is the nicest:

{this.state.yourVariable === 'news' && <Text>{data}<Text/>}