8000 add create-react-node-with-jsx.md · learnreactjs/learnreactjs@69f0f4d · GitHub
[go: up one dir, main page]

Skip to content

Commit 69f0f4d

Browse files
committed
add create-react-node-with-jsx.md
1 parent b2c3569 commit 69f0f4d

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Creating React Nodes With JSX
2+
3+
Go through the previous chapter you should be familiar with creating React nodes using the `React.createElement()` function. Below I use this familiar function to create one React nodes:
4+
5+
```javascript
6+
//React node, which represents an actual HTML DOM node
7+
var HTMLLi = React.createElement('li', {className:'bar'}, 'foo');
8+
```
9+
10+
To use JSX instead (assuming you have Babel setup) of `React.createElement()` to create these React nodes one just has to replace React.createElement() function calls with the HTML/XML like tags which represent the HTML you'd like the virtual DOM to spit out. The above code can be written in JSX like so:
11+
12+
```javascript
13+
//React node, which represents an actual HTML DOM node
14+
var HTMLOption = <option value="1">one</option>;
15+
```
16+
17+
Notice that the JSX is not in a JavaScript string format and can just be writing as if you are writing it inside of an `.html` file.
18+
19+
JSX is transformed back into the `React.createElement()` functions calls by Babel. You can see the transformation below:
20+
21+
<p data-height="265" data-theme-id="dark" data-slug-hash="odJLPe" data-default-tab="js,result" data-user="Bunlong" data-embed-version="2" data-pen-title="odJLPe" class="codepen">See the Pen <a href="https://codepen.io/Bunlong/pen/odJLPe/">odJLPe</a> by Bunlong (<a href="https://codepen.io/Bunlong">@Bunlong</a>) on <a href="https://codepen.io">CodePen</a>.</p>
22+
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>
23+
24+
HTML produced in the above CodePen it would look like so:
25+
26+
```javascript
27+
<body>
28+
<div id="app"><option value="1" data-reactid=".0">one</li></div>
29+
</body>
30+
```
31+
32+
Creating React nodes using JSX is as simple as writing HTML like code in your JavaScript files.
33+
34+
Note:
35+
36+
* The `class` attribute has to be written `className`
37+
* The `for` attribute has to be written `htmlFor`
38+
* The style attribute takes an object of [camel-cased style properties](https://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSS2Properties)
39+
* All attributes are camel-cased (e.g. `accept-charset` is written as `acceptCharset`)

0 commit comments

Comments
 (0)
0