mercredi 22 août 2018

Only ternary operator works here

I am a beginner to React. I just tried the following code:

class Contact extends React.Component {
  render() {
    return (
      <div id="authorization">
        <h1>
          { 
            if (this.state.authorized) {
             'Contact'
            } else {
             'Enter the Password'
            } 
          }     
        </h1>
    )
  }
}

As you can see in the above code, I have put a JS if-else code in between a pair of curly braces {}, because I read it on Introducing JSX that

You can put any valid JavaScript expression inside the curly braces in JSX.

But the above code just didn't work. But if I replace it with a ternary operator:

<h1>
  { this.state.authorized ? 'Contact' : 'Enter the Password' }
</h1>

it works! Is that there are some situations under which I can only use ternary operator but not usual JS if-else statement?

Aucun commentaire:

Enregistrer un commentaire