Modelesq Modelesq - 1 year ago 89
Javascript Question

ternary operator in jsx to include html with react

I'm using react and I'm trying to display this error message if

this.state.message === 'failed'
. But I'm really not sure why this ternary operation isn't working. What am I doing wrong here?

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

Right now its just displaying
return (this.state.message === 'failed') ? ( =>
in the html

Answer Source

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> 

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..