0

I'm getting an error message 'Expecting '}'' just before calling the Function Expression in code given below.

class IfElse extends React.Component{
    render(){
        return(
            <div>
                {
                    (booleanExp)=>{
                        return(
                        <a href={(booleanExp)?'login':'logout'}>{(booleanExp)?'login':'logout'}</a>
                        )
                    }(this.props.booleanExp)
                }
            </div>
            
        )
    }
};

The error is here: }(this.props.booleanExp), just after the curly brace. If i remove the function invocation, then there is no error But function call is required for me.

abdullahQureshee
  • 322
  • 2
  • 12

3 Answers3

1

Wrap the function in ( and ).

E.g:

((booleanExp)=>{
    return(
        <a href={(booleanExp)?'login':'logout'}>{(booleanExp)?'login':'logout'}</a>
    )
})(this.props.booleanExp)

namgold
  • 1,009
  • 1
  • 11
  • 32
  • Yes that worked! I really appreciate your contribution. I'll request you to explain the problem and why the brackets solved them, if you like, otherwise you have the upvote. – abdullahQureshee Sep 25 '20 at 11:50
  • Please refer [this](https://stackoverflow.com/questions/34589488/es6-immediately-invoked-arrow-function) – namgold Sep 28 '20 at 03:06
0
class IfElse extends React.Component {
  render() {
    return (
      <div>
        {
          (booleanExp) => (
            <a href={(booleanExp) ? 'login' : 'logout'}>{(booleanExp) ? 'login' : 'logout'}</a>
          )(this.props.booleanExp)
        }
      </div>

    )
  }
};
Veno
  • 433
  • 2
  • 14
  • Nope! it Doesn't work. Its just the simple JavaScript Inline undefined kind of function and I'm sure that only curly braces are used for the body. – abdullahQureshee Sep 25 '20 at 11:59
0

Why do you need to invoke a function inside of render method? Can you simply use ternary expression:

class IfElse extends React.Component{
    render(){
        return(
            <div>
                <a href={this.props.booleanExp ? 'login' : 'logout'}> 
                  {this.props.booleanExp ? 'login' : 'logout'}
                </a>
            </div>
            
        )
    }
};

or even simplify it to a functional component:

const IfElse = ({booleanExp}) => (
 <div>
   <a href={booleanExp ? 'login' : 'logout'}> 
     {booleanExp ? 'login' : 'logout'}
   </a>
 </div>
);
Anastasiia Solop
  • 1,313
  • 10
  • 20