new entry for ternary expression in jsx
Cheng Lou committed
Sep 27, 2013 at 02:21 UTC
0fad22512ac5cb56e400cadfeaafa02387282ec1
2 files changed
+67
docs/cookbook/cb-03-if-else-in-JSX tip.md
new
+31
@@ -0,0 +1,31 @@
1
+---
2
+id: if-else-in-JSX-tip
3
+title: If-Else in JSX
4
+layout: docs
5
+permalink: inline-styles.html
6
+script: "cookbook/inline-styles.js"
7
+---
8
+
9
+`if-else` statements don't work inside JSX, since JSX is really just sugar for functions:
10
+
11
+```html
12
+/** @jsx React.DOM */
13
+
14
+// this
15
+React.renderComponent(<div id="msg">Hello World!</div>, mountNode);
16
+// is the same as this
17
+React.renderComponent(React.DOM.div({id:"msg"}, "Hello World!"), mountNode);
18
+```
19
+
20
+Which means `<div id={if (true){ 'msg' }}>Hello World!</div>` doesn't make sense, as (if it worked) it would be compiled down to something like this `React.DOM.div({id: if (true){ 'msg' }}, "Hello World!")`, which isn't valid JS.
21
+
22
+What you're searching for is ternary expression:
23
+
24
+```html
25
+/** @jsx React.DOM */
26
+
27
+// this
28
+React.renderComponent(<div id={true ? 'msg' : ''}>Hello World!</div>, mountNode);
29
+```
30
+
31
+Try the [JSX compiler](http://facebook.github.io/react/jsx-compiler.html) to see how this works. It's a very simple transformation, thus making JSX entirely optional to use with React.
docs/cookbook/cb-03-if-else-in-JSX.md
new
+36
@@ -0,0 +1,36 @@
1
+---
2
+id: if-else-in-JSX
3
+title: If-Else in JSX
4
+layout: docs
5
+permalink: inline-styles.html
6
+script: "cookbook/inline-styles.js"
7
+---
8
+
9
+### Problem
10
+You want to use conditional in JSX.
11
+
12
+### Solution
13
+Don't forget that JSX is really just sugar for functions:
14
+
15
+```html
16
+/** @jsx React.DOM */
17
+
18
+// this
19
+React.renderComponent(<div id="msg">Hello World!</div>, mountNode);
20
+// is the same as this
21
+React.renderComponent(React.DOM.div({id:"msg"}, "Hello World!"), mountNode);
22
+```
23
+
24
+Which means `<div id={if (true){ 'msg' }}>Hello World!</div>` doesn't make sense, as (if it worked) it would be compiled down to something like this `React.DOM.div({id: if (true){ 'msg' }}, "Hello World!")`, which isn't valid JS.
25
+
26
+What you're searching for is ternary expression:
27
+
28
+```html
29
+/** @jsx React.DOM */
30
+
31
+// this
32
+React.renderComponent(<div id={true ? 'msg' : ''}>Hello World!</div>, mountNode);
33
+```
34
+
35
+### Discussion
36
+Try the [JSX compiler](http://facebook.github.io/react/jsx-compiler.html) to see how this works. It's a very simple transformation, thus making JSX entirely optional to use with React.