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 Answers3

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>
);
Stretch0
  • 8,362
  • 13
  • 71
  • 133
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>
        );
    }
}
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
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>
    );
  }
}  
VilleKoo
  • 2,827
  • 2
  • 14
  • 23