@samitouri / QOS-React-2 / commits / 9a2e5f2cc5

Add IIFE example to JSX documentation

Luke Horvat committed Jun 16, 2015 at 19:46 UTC 9a2e5f2cc5386219f629da3cce6b01aa84bb3158
1 file changed +29 -3
docs/tips/03-if-else-in-JSX.md
+29 -3
@@ -33,8 +33,7 @@ That's not valid JS. You probably want to make use of a ternary expression:
33 React.render(<div id={condition ? 'msg' : ''}>Hello World!</div>, mountNode);
34 ```
35
36 -If a ternary expression isn't robust enough, you can use `if` statements to determine which
37 -components should be used.
36 +If a ternary expression isn't robust enough, you can use `if` statements outside of your JSX to determine which components should be used:
37
38 ```js
39 var loginButton;
@@ -49,7 +48,34 @@ return (
48 <Home />
49 {loginButton}
50 </nav>
52 -)
51 +);
52 ```
53
54 +Or if you prefer a more "inline" aesthetic, define [immediately-invoked function expressions](https://en.wikipedia.org/wiki/Immediately-invoked_function_expression) _inside_ your JSX:
55 +
56 +```js
57 +return (
58 + <section>
59 + <h1>Color</h1>
60 + <h3>Name</h3>
61 + <p>{this.state.color || "white"}</p>
62 + <h3>Hex</h3>
63 + <p>
64 + {() => {
65 + switch (this.state.color) {
66 + case "red": return "#FF0000";
67 + case "green": return "#00FF00";
68 + case "blue": return "#0000FF";
69 + default: return "#FFFFFF";
70 + }
71 + }()}
72 + </p>
73 + </section>
74 +);
75 +```
76 +
77 +> Note:
78 +>
79 +> In the example above, an ES6 [arrow function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) is utilized to lexically bind the value of `this`.
80 +
81 Try using it today with the [JSX compiler](/react/jsx-compiler.html).