Cannot render boolean value in JSX?

JavascriptReactjsReact Jsx

Javascript Problem Overview


I am trying to render boolean value inside JSX, however React is evaluating it as expression and isn't returning anything after the component is returned.

Any workaround for this?

Here is an example

var ipsumText = true;

ReactDOM.render(
  <div>
     Boolean Value:    {ipsumText}
  </div>,
  document.getElementById('impl')
);

Just shows compiled HTML as

<div data-reactid=".0"><span data-reactid=".0.0">Boolean Value:    </span></div>

EDIT: Here is the JSBin link for the example http://jsbin.com/nibihodoce/1/edit?html,js,output

EDIT 2: I have already explored the .toString() alternative, however since I am iterating over an array of objects and a particular field of that object can have string/integer/boolean kind of value. Applying .toString() to all of 'em doesn't seem optimal.

Javascript Solutions


Solution 1 - Javascript

Boolean Value: { ipsumText.toString() }

or

Boolean Value: { String(ipsumText) }

or

Boolean Value: { '' + ipsumText }

or

{`Boolean Value: ${ipsumText}`}

or

Boolean Value: { JSON.stringify(ipsumText) }

I prefer the second option. Universal, fast, works for all primitive types: Boolean( smth ), Number( smth ).

Solution 2 - Javascript

You can convert boolean value to string, concatenating it with empty string:

var ipsumText = true;

ReactDOM.render(
  <div>
     Boolean Value: {ipsumText + ''}
  </div>,
  document.getElementById('impl')
);

Or you can do it, when assigning bool value to variable:

var ipsumText = true + '';

ReactDOM.render(
  <div>
     Boolean Value: {ipsumText}
  </div>,
  document.getElementById('impl')
);

If your variable can have not boolean value, you should convert it to boolean:

// `ipsumText` variable is `true` now.
var ipsumText = !!'text';

Solution 3 - Javascript

<select>
    <option value={row.feature_product ? true: true || row.feature_product ? false: false}>
    {`${row.feature_product}`}
    </option>
    <option value={row.feature_product ? false: true || row.feature_product ? true: false}>
    {`${row.feature_product ? false: true}` || `${row.feature_product ? true: false}`}
    </option>
</select>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionanuj_ioView Question on Stackoverflow
Solution 1 - JavascriptgapertonView Answer on Stackoverflow
Solution 2 - Javascript1venView Answer on Stackoverflow
Solution 3 - JavascriptJake SmithView Answer on Stackoverflow