If-Else in JSX

if-else statements don’t work inside JSX. This is because JSX is just syntactic sugar for function calls and object construction. Take this basic example:

  1. // This JSX:
  2. ReactDOM.render(<div id="msg">Hello World!</div>, mountNode);
  3. // Is transformed to this JS:
  4. ReactDOM.render(React.createElement("div", {id:"msg"}, "Hello World!"), mountNode);

This means that if statements don’t fit in. Take this example:

  1. // This JSX:
  2. <div id={if (condition) { 'msg' }}>Hello World!</div>
  3. // Is transformed to this JS:
  4. React.createElement("div", {id: if (condition) { 'msg' }}, "Hello World!");

That’s not valid JS. You probably want to make use of a ternary expression:

  1. ReactDOM.render(<div id={condition ? 'msg' : null}>Hello World!</div>, mountNode);

If a ternary expression isn’t robust enough, you can use if statements outside of your JSX to determine which components should be used:

  1. var loginButton;
  2. if (loggedIn) {
  3. loginButton = <LogoutButton />;
  4. } else {
  5. loginButton = <LoginButton />;
  6. }
  7. return (
  8. <nav>
  9. <Home />
  10. {loginButton}
  11. </nav>
  12. );

Or if you prefer a more “inline” aesthetic, define immediately-invoked function expressions inside your JSX:

  1. return (
  2. <section>
  3. <h1>Color</h1>
  4. <h3>Name</h3>
  5. <p>{this.state.color || "white"}</p>
  6. <h3>Hex</h3>
  7. <p>
  8. {(() => {
  9. switch (this.state.color) {
  10. case "red": return "#FF0000";
  11. case "green": return "#00FF00";
  12. case "blue": return "#0000FF";
  13. default: return "#FFFFFF";
  14. }
  15. })()}
  16. </p>
  17. </section>
  18. );

Note:

In the example above, an ES6 arrow function is utilized to lexically bind the value of this.

Try using it today with the Babel REPL.