ternary operator in jsx to include html with react

I currently like to format my ternaries like this in react:

render () {
  return (
    <div className="row">
      { //Check if message failed
        (this.state.message === 'failed')
          ? <div> Something went wrong </div> 
          : <div> Everything in the world is fine </div> 
      }
    </div>
  );
}

You are correct that IIFEs can be used within a render statement as well as ternary expressions. Using a normal if .. else statement is valid, but the render function's return statement can only contain expressions so you would have to do those elsewhere..


The syntax for ternary is condition ? if : else. To be safe, you can always wrap the entire ternary statement inside parenthesis. JSX elements are also wrapped in parenthesis. The fat arrow in an arrow function is always preceeded by two parenthesis (for the arguments) - but you don't need any functions here anyway. So given all of that, there are a couple of syntax errors in your code. Here's a working solution:

render() {
  return (this.state.message === 'failed' ? (
   <div className="alert alert-danger" role="alert">
     Something went wrong
   </div>
  ) : null);
}

Edit: if this is inside other markup, then you don't need to call render again. You can just use curly braces for interpolation.

render() {
  return (
    <div className="row">
      {this.state.message === 'failed' ? (
       <div className="alert alert-danger" role="alert">
         Something went wrong
       </div>
      ) : null}
    </div>
  );
}