title: React Native: How to add variables inside View?
body: <p>I have the following React Native code:</p>
  
  <pre><code>&lt;View&gt;
    {
      a
      ?
      (
        &lt;View/&gt;
      )
      :
      (
        &lt;View/&gt;
      )
    }
  &lt;/View&gt;
  </code></pre>
  
  <p>I want to create a variable in the first branch of the ternary statement, and thought I could do so like this:</p>
  
  <pre><code>&lt;View&gt;
    {
      a
      ?
      {
        let b = 1;
        return &lt;View/&gt;
      }
      :
      (
        &lt;View/&gt;
      )
    }
  &lt;/View&gt;
  </code></pre>
  
  <p>This gives me the following two Typescript errors, and causes the app to crash: "Left side of comma operator is unused and has no side effects." and "Operator '&lt;' cannot be applied to types '{ return(): any; }' and 'typeof View'"</p>
  
  <p>I have replaced <code>()</code> with <code>{return ...}</code> in React Native before, and can't understand why it doesn't work here. Any ideas?</p>
  
  <p><strong>EDIT: SOLUTION</strong></p>
  
  <p>The problem is that where in some areas of Javascript you can use <code>{return ...}</code> in place of <code>()</code>, ternary operators are not one of them. For example, with an array method like <code>map()</code> the following two pieces of code are equivalent:</p>
  
  <pre><code>array.map(item =&gt; {return 1})
  array.map(item =&gt; (1))
  </code></pre>
  
  <p>but the following two are not (the first is valid, the second throw an error):</p>
  
  <pre><code>let a = true ? (1) : (2)
  let a = true ? {return 1} : {return 2}
  </code></pre>
  
  <p>The solution for my scenario is to define the variable just outside the JSX. In this case:</p>
  
  <pre><code>render() {
      let b = 1
      return (
          &lt;View&gt;
          {
          a
          ?
          (
              &lt;View/&gt;
          )
          :
          (
              &lt;View/&gt;
          )
          }
          &lt;/View&gt;
      )
  }
  </code></pre>