Jessie Campbell Jessie Campbell - 1 month ago 12
React JSX Question

If else causes unexpected token in ES6

I think I've wrapped brackets properly but I am still getting an error:

Uncaught Error: Parse Error: Line 22: Unexpected token if

if(this.state.isEditing) {
^


Here's a JSFiddle

Relevant code

...
renderItem(){
return (
if(this.state.isEditing) {
<input type="text" />
<button>Save</button>
} else {
this.state.items.map((item, i) =>
<li key={i}>
{item}&nbsp;
<button>Edit</button>
<button onClick={this.dlt_item.bind(this, i)}>Delete</button>
</li>
)
}
)
},
...

Answer

You cannot have an if-else statement in a return function. Also You can also make use of ternary operators instead of if-else. Also I would recommend you do have a go at some of the basic react tutorials that will get you basics clear on some of the important syntax's

Also React clearly tells you what the error is. Just search for that error and you can easily find your problem. Also you should first try to see where exacty the error points at and then debug with a proper method. Hope this helps and you can debug the rest of the errors on your own.

Do it this way

renderItem(){
   var renderIt = null;
   if(this.state.isEditing){
    renderIt =  <div><input type="text" />
                <button>Save</button></div>
   }else{
      renderIt = this.state.items.map((item,i)=> <li key={i}>{item}
   &nbsp;
   <button>Edit</button>
   <button onClick={this.dlt_item.bind(this,i)}>Delete</button>
   </li>
   )
   }
   return (
   <div>{renderIt}</div>


   )
   },

JSFIDDLE

var App = React.createClass({
   getInitialState(){
   return {
     items:[1,2,3],
     isEditing:false
   }
   },
   dlt_item(key){
   var newItems = this.state.items.filter((item,i)=> i !== key)
   this.setState({items:newItems})
   },
   edit_handler(){
   this.setState({isEditing:true})
   },
   isEditing_html(){
    return(
     <div>
     <input type="text" />
     <button>Save</button>
     </div>
     )
   },
   renderItem(){

   return(

      this.state.items.map(function(item,i) {

       var temp = null;
       if(this.state.isEditing){
   temp = this.isEditing_html()
   }else{
   temp = <div><button>Edit</button>
   <button onClick={this.dlt_item.bind(this,i)}>Delete</button></div>
   }
      return (<li key={i}>{item}
   &nbsp;
   {temp}
   </li>

   )
   }.bind(this)
   )
   )
   },
   render(){
      return(
      <ul>
        {this.renderItem()}
      </ul>
      )
   }
})

React.render(<App />, document.getElementById('container'));

JSFIDDLE

Comments