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.
The JSX transformation will result in the follow:
var label = '2 + 2';
var inputType = 'input';
var reactNode = React.createElement(
'label',
null,
label,
' = ',
React.createElement('input', { type: inputType, value: 2 + 2 })
);
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:
<div id="app1">
<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>
</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
{'{}'}
.