@samitouri / QOS-React-2 / commits / 684e5922e8

Tweaks to if-else tip

Paul O’Shannessy committed Nov 12, 2013 at 12:48 UTC 684e5922e81566de41cf468d411bd447df8ab9f7
1 file changed +18 -7
docs/tips/03-if-else-in-JSX.md
+18 -7
@@ -7,25 +7,36 @@ prev: inline-styles.html
7 next: self-closing-tag.html
8 ---
9
10 -`if-else` statements don't work inside JSX, since JSX is really just sugar for functions:
10 +`if-else` statements don't work inside JSX. This is because JSX is just syntactic sugar for function calls and object construction. Take this basic example:
11
12 ```js
13 /** @jsx React.DOM */
14
15 -// this
15 +// This JSX:
16 React.renderComponent(<div id="msg">Hello World!</div>, mountNode);
17 -// is the same as this
17 +
18 +// Is transformed to this JS:
19 React.renderComponent(React.DOM.div({id:"msg"}, "Hello World!"), mountNode);
20 ```
21
21 -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.
22 +This means that `if` statements don't fit in. Take this example:
23 +
24 +```js
25 +/** @jsx React.DOM */
26 +
27 +// This JSX:
28 +<div id={if (condition) { 'msg' }}>Hello World!</div>
29 +
30 +// Is transformed to this JS:
31 +React.DOM.div({id: if (condition) { 'msg' }}, "Hello World!");
32 +```
33
23 -What you're searching for is ternary expression:
34 +That's not valid JS. You probably want to make use of a ternary expression:
35
36 ```js
37 /** @jsx React.DOM */
38
28 -React.renderComponent(<div id={true ? 'msg' : ''}>Hello World!</div>, mountNode);
39 +React.renderComponent(<div id={condition ? 'msg' : ''}>Hello World!</div>, mountNode);
40 ```
41
31 -Try the [JSX compiler](/react/jsx-compiler.html).
42 +Try using it today with the [JSX compiler](/react/jsx-compiler.html).