Using JavaScript Expressions in JSX

Hopefully by now it’s obvious that JSX is just syntactical sugar that gets converted to real JavaScript. But what happens when you want to intermingle real JavaScript code within JSX? To write a JavaScript expression within JSX you will have to surround the JavaScript code in { } brackets.

In the React/JSX code below I am mixing JavaScript expressions (e.g., 2+2), surround by { } among the JSX that will eventually get evaluated by JavaScript.

source code

The JSX transformation will result in the follow:

  1. var label = '2 + 2';
  2. var inputType = 'input';
  3. var reactNode = React.createElement(
  4. 'label',
  5. null,
  6. label,
  7. ' = ',
  8. React.createElement('input', { type: inputType, value: 2 + 2 })
  9. );
  10. ReactDOM.render(reactNode, document.getElementById('app1'));

Once this code is parsed by a JavaScript engine (i.e., a browser) the JavaScript expressions are evaluated and the resulting HTML will look like so:

  1. <div id="app1">
  2. <label data-reactid=".0"><span data-reactid=".0.0">2 + 2</span><span data-reactid=".0.1"> = </span><input type="input" value="4" data-reactid=".0.2"></label>
  3. </div>

Nothing that complicated is going on here once you realize that the brackets basically escape the JSX. The { } brackets simply tells JSX that the content is JavaScript so leave it alone so it can eventually be parsed by a JavaScript engine (e.g., 2+2). Note that { } brackets can be used anywhere among the JSX expressions as long as the result is valid JavaScript.

Notes

  • If you have to escape brackets (i.e., you want brackets in a string) use {'{}'}.