Abhi Pavithran Abhi Pavithran - 3 months ago 31
Javascript Question

why if-else condition is not working while using in react jsx

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?

Answer

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 a self-executing function and pass the value returned from within:

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

which will compile into the following valid Javascript:

React.createElement(
    "div",
    {
        id: (function (condition) {
            if (condition) {
                return "msg";
            } else {
                return null;
            }
        })(condition)
    },
    "Hello World!"
);

Note: based on my experience, specifying null for a component property might have side-effects, like the component not re-rendering if a non-null value was passed earlier. It might be better to specify "" instead.