1

I cannot get browserify to compile a react file in which I'm trying to use a conditional to render.

The render function:

render() {
    const hasObjects = this.state.objects.length === 0 ? false : true;
    return {hasObjects ? (<p> Objects </p>) : (<p>No objects are available.</p>)};   
}   

When I try to compile with browserify, I get the following error.

SyntaxError: ~/Projects/Project/src/index.js: Unexpected token, expected , (26:27)
  24 |     render() {
  25 |         const hasObjects = true;
 >26 |         return {hasObjects ? (<p> Objects </p>) : (<p>No objects are available.</p>)}
     |                            ^
  27 |     }
  28 | 

I compile with browserify src/index.js -o static/js/bundle.js -t [ babelify --presets [ env react ] ]

and my .bablerc is:

{
     "plugins": [
         "react-html-attrs",
     ]
}

The documentation for react indicates that the conditional is a valid option for conditional rendering so I assume that this is a browserify issue. What option can I set to compile this file?

K. Shores
  • 875
  • 1
  • 18
  • 46

2 Answers2

2

You don't need to wrap your expression in {...}, that is only required when passing an expression as a child in JSX. When you leave the braces there, JavaScript thinks you are returning an object.

Just remove the braces:

render() {
  const hasObjects = true;
  return hasObjects ? (<p> Objects </p>) : (<p>No objects are available</p>);
}
Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170
  • Alas, this is correct. After reviewing the documentation, the conditional that they had used was already inside of a div so I thought it was necessary. – K. Shores Mar 30 '18 at 16:55
0

No need to wrap your expression in {...}
You might change your code to this:
render() { const hasObjects = true; return hasObjects ? (<p> Objects </p>) : (<p>No objects are available</p>); } This will work.