3

I am trying to check if a prop is empty and add a condition to a react component.

Here is the code:

class Mycomp extends Component {

    render() {
        return (
            <div className="Mycomp">
                {this.props.title}
                if (this.props.title != '') {
                    console.log('Title is not empty');
                }
            </div>
        );
    }
}

The problem is that I'm getting an Unexpected Token error.

How can I fix this?

3
  • 2
    Move your if condition before the return statement. (and use !== btw) Commented Mar 9, 2018 at 9:59
  • you can not have if statement in your JSX Commented Mar 9, 2018 at 10:09
  • { this.props.title || console.log("title is empty") } Commented Mar 9, 2018 at 10:27

3 Answers 3

1

You can't have an if statement in your JSX like that. You are best to use turnery operators or do something like this:

return (
  <div className="Mycomp">
        {this.props.title ||''} 
  </div>
);
Sign up to request clarification or add additional context in comments.

Comments

0

You cannot have a if-else statement in return, use a ternary operator

class Mycomp extends Component {

    render() {
        if (this.props.title != '') {
            console.log('Title is not empty');
        }
        return (
            <div className="Mycomp">
                {this.props.title}
                {this.props.title? 'Something here': 'Else something'}
            </div>
        );
    }
}

Comments

0

One more option is to use logical operator &&

class Mycomp extends React.Component {
  render() {
    const title = this.props.title
    return (
      <div className="Mycomp">
         { title && title }
      </div>
    );
  }
}  

1 Comment

Or... { title }