Skip to content

Commit 7948c27

Browse files
committed
add define-attribute-props-in-jsx.md
1 parent fd98fa1 commit 7948c27

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# Defining Attributes/Props in JSX
2+
3+
JSX is used to express XML-like nodes that get turned into HTML, attribute/props are defined by adding the attributes/props to JSX expressions as name-value attributes.
4+
5+
In the example below I am defining a React `<li>` element node, using JSX, with five attributes/props. One is a non-standard HTML attribute and the others are known HTML attributes.
6+
7+
```javascript
8+
var styles = {backgroundColor:'red'};
9+
var tested = true;
10+
var text = 'text';
11+
12+
var reactNodeLi = <li id=""
13+
data-test={tested?'test':'false'}
14+
className="blue"
15+
aria-test="test"
16+
style={styles}
17+
foo="bar">
18+
{text}
19+
</li>;
20+
21+
ReactDOM.render(reactNodeLi, document.getElementById('app'));
22+
```
23+
24+
The JSX when it is transformed will look like this (note that attributes/props just become arguments to a function):
25+
26+
```javascript
27+
var reactNodeLi = React.createElement(
28+
'li',
29+
{
30+
id: '',
31+
'data-test': tested ? 'test' : 'false',
32+
className: 'blue',
33+
'aria-test': 'test',
34+
style: styles,
35+
foo: 'bar'
36+
},
37+
text
38+
);
39+
40+
```
41+
42+
When the `reactNodeLi` node is render to the DOM it will look like this:
43+
44+
```javascript
45+
<div id="app1">
46+
<li id="true"
47+
data-test="test"
48+
class="blue"
49+
aria-test="test"
50+
style="background-color:red;"
51+
data-reactid=".0">
52+
text
53+
</li>
54+
</div>
55+
```
56+
57+
You should note the following:
58+
59+
* Leaving an attribute/prop blank results in that attribute value becoming true (e.g. `id=""` becomes `id="true"` and test becomes `test="true"`)
60+
* The `foo` attribute, because it was not a standard HTML attribute, doesn't become a final HTML attribute.
61+
62+
Note:
63+
64+
* The `class` attribute has to be written `className`
65+
* The `for` attribute has to be written `htmlFor`
66+
* The `style` attribute takes a reference to an object of [camel-cased style properties](https://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSS2Properties)
67+
* All attributes are camel-cased (e.g. `accept-charset` is written as `acceptCharset`) which differs from how they are written in HTML.

0 commit comments

Comments
 (0)