Dave Sag Dave Sag - 16 days ago 9
React JSX Question

React, Babel — Nesting conditions within a JSX block doesn't work

I have what I'd hope is a fairly normal setup for coding React with ES6 syntax, namely I am using Babel to transpile and Webpack to assemble the code.

This is how I have Babel configured (extracted from package.json)

"babel": {
"presets": [
["es2015", {"loose": true}],
"stage-0",
"react"
],
"plugins": [
"react-hot-loader/babel"
]
},


When conditionally rendering content within a JSX block using React, if I do this

{showingVoterList && (
{!!message && (
<Panel header='Could not load voters' bsStyle='danger'>
<p>{message}</p>
</Panel>
)}
{!message && (
<p>Voter list goes here</p>
)}
)}


I get this error:

Module build failed: SyntaxError: Unexpected token (53:11)

51 |
52 | {showingVoterList && (
> 53 | {!!message && (
| ^
54 | <Panel header='Could not load voters' bsStyle='danger'>
55 | <p>{message}</p>
56 | </Panel>


but if I do this, it works fine

{showingVoterList && !!message && (
<Panel header='Could not load voters' bsStyle='danger'>
<p>{message}</p>
</Panel>
)}
{showingVoterList && !message && (
<p>Voter list goes here</p>
)}


Why can't the conditions be nested?

Answer

The example you have provided is not valid JavaScript inside a JSX tag.

The second brace where the error occurs is interpreted as an Object, which is why it is not expecting the token !;

If you wanted to keep this code inline you could convert it to use a ternary like this:

{showingVoterList && (
  !!message 
    ? <Panel header='Could not load voters' bsStyle='danger'>
        <p>{message}</p>
      </Panel>
    : <p>Voter list goes here</p>
)}