6

writing if-else in jsx while writing react code is not working.

<div id={if (condition) { 'msg' }}>Hello World!</div>

However using ternary operator works.

<div id={condition ? 'msg' : null}>Hello World!</div>

why is this happening?

1
  • because if isn't an rvalue? Commented Aug 23, 2016 at 10:38

3 Answers 3

4

Your JSX of

<div id={condition ? 'msg' : null}>Hello World!</div>

which is not valid Javascript by itself, will be compiled into the following ReactJS call:

React.createElement(
  'div',                            // Element "tag" name.
  { id: condition ? 'msg' : null }, // Properties object.
  'Hello World!'                    // Element contents.
);

which is valid Javascript, ready to be interpreted/compiled by your Javascript runtime environment. As you can see, there is no way to jam an if-else into that statement, as it cannot be compiled into valid Javascript.


You could instead use an immediately-invoked function expression and pass the value returned from within:

<div id={(function () {
    if (condition) {
        return "msg";
    } else {
        return null;
    }
})()}>Hello World!</div>

which will compile into the following valid Javascript:

React.createElement(
    "div",
    {
        id: (function () {
            if (condition) {
                return "msg";
            } else {
                return null;
            }
        })()
    },
    "Hello World!"
);
Sign up to request clarification or add additional context in comments.

Comments

2

if-else statements don't work inside JSX. This is because JSX is just syntactic sugar for function calls and object construction. React Docs

Comments

1
// This JSX:
<div id={if (condition) { 'msg' }}>Hello World!</div>

// Is transformed to this JS:
React.createElement("div", {id: if (condition) { 'msg' }}, "Hello World!");

So, you see if/else does not fit in this model. Better to use it outside of jsx. may be in render function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.