Immediate function expression inside JSX

I am working on a React project where I am trying to compile but cannot find why I am getting this syntax error. In particular, what does the "{() => {} ()}" pattern do in this context?

Module build failed: SyntaxError: Unexpected token, expected } (35:9)

33 |             return (<div className="loading" />);
34 |           } 
35 |         }()}
   |          ^
36 |       </div>
37 |     );
38 |   }

@ ./src/containers/SearchApp.js 7:0-52
@ ./src/containers/App.js
@ ./src/index.js
@ multi ./src/index

      


Part of the code:

render() {
return (
  <div>
    <div className="form-group">
      <input onKeyDown={this.searchEnter.bind(this)} type="text" ref="tag" className="form-control input-lg search-bar" placeholder="Enter the tag..." />
      <button onClick={this.searchClick.bind(this)} type="button" className="btn btn-default search-button">Search!</button>
    </div>
    {()=>{
      if (this.props.status === 'PENDING') {
        return (<div className="loading" />);
      }
    }()}
  </div>
);

      

+3


source to share


1 answer


This is an Immediate Function Expression .

Error with code?

You need to wrap the inside () function, Check this:

{
   (() => {
      if (this.props.status === 'PENDING') {
         return (<div className="loading" />);
      }
   })()
}

      

what does the pattern "{() => {} ()} work in this context?



We cannot directly put an if / else statement or any other statement inside JSX, so for this we need to create a function and put all the logic in it.

Like DOC :

If-else statements don't work inside JSX. This is because JSX is just syntactic sugar for calling functions and constructing an object. If the ternary expression isn't stable enough, you can use if statements outside of your JSX to determine which components should be used. Or, if you prefer a more "inline" aesthetic, define hot-call function expressions within your JSX.

Another way to write the same code:

render(){
    return(
        <div>
            <div className="form-group">
                ....   
            </div>
            {this._callFun()}    
        </div>
    )
}

_callFun(){
    if (this.props.status === 'PENDING') {
        return (<div className="loading" />);
    }
}

      

+3


source







All Articles