10000 add use-javascript-expression-in-jsx.md · learnreactjs/learnreactjs@e762ea1 · GitHub
[go: up one dir, main page]

Skip to content

Commit e762ea1

Browse files
committed
add use-javascript-expression-in-jsx.md
1 parent 50b04a7 commit e762ea1

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Using JavaScript Expressions in JSX
2+
3+
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.
4+
5+
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.
6+
7+
<p data-height="265" data-theme-id="dark" data-slug-hash="xjmRgB" data-default-tab="js,result" data-user="Bunlong" data-embed-version="2" data-pen-title="xjmRgB" class="codepen">See the Pen <a href="https://codepen.io/Bunlong/pen/xjmRgB/">xjmRgB</a> by Bunlong (<a href="https://codepen.io/Bunlong">@Bunlong</a>) on <a href="https://codepen.io">CodePen</a>.</p>
8+
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>
9+
10+
The JSX transformation will result in the follow:
11+
12+
```javascript
13+
var label = '2 + 7';
14+
var inputType = 'input';
15+
16+
var reactNode = React.createElement(
17+
'label',
18+
null,
19+
label,
20+
' = ',
21+
React.createElement('input', { type: inputType, value: 2 + 7 })
22+
);
23+
24+
ReactDOM.render(reactNode, document.getElementById('app'));
25+
```
26+
27+
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:
28+
29+
```javascript
30+
<div id="app">
31+
<label data-reactid=".0"><span data-reactid=".0.0">2 + 7</span><span data-reactid=".0.1"> = </span><input type="input" value="9" data-reactid=".0.2"></label>
32+
</div>
33+
```
34+
35+
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+7). Note that `{ }` brackets can be used anywhere among the JSX expressions as long as the result is valid JavaScript.
36+
37+
Note:
38+
39+
* If you have to escape brackets (i.e. you want brackets in a string) use `{'{}'}`.

0 commit comments

Comments
 (0)
0