0

I am trying to write a nested IF ELSE condition in JSX but its not working. Can anyone please help how to write the below condition in JSX?

if (content) {
    if (content.flag) {
        <showSomeComponent />
    }else if (!content.flag) {
        <showSomeOtherComponent />
    }
}

Thanks in advance.

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Max
  • 25
  • 1
  • 8
  • Does this answer your question? [if-else statement inside jsx: ReactJS](https://stackoverflow.com/questions/44046037/if-else-statement-inside-jsx-reactjs) – Emile Bergeron Apr 22 '20 at 14:27

2 Answers2

2

You need a return statement and Uppercased component name:

if (content) {
  if (content.flag) {
    return <ShowSomeComponent />;
  } else {
    return <ShowSomeOtherComponent />;
  }
}

Note: Always start component names with a capital letter. React treats components starting with lowercase letters as DOM tags.

Or with optional chaining and ternary operator:

// return content && content.flag ? <ShowSomeComponent /> : <ShowSomeOtherComponent />
return content?.flag ? <ShowSomeComponent /> : <ShowSomeOtherComponent />;
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
1

You could write it in

const asd = content && content.flag ? <ShowSomeComponent /> : <ShowSomeOtherComponent />

const asd = content && content.flag && <ShowSomeComponent /> || <ShowSomeOtherComponent />

return content && content.flag && <ShowSomeComponent /> || <ShowSomeOtherComponent />

return content?.flag ? <ShowSomeComponent /> : <ShowSomeOtherComponent />;
Han
  • 361
  • 1
  • 6