Created
July 19, 2015 04:31
-
-
Save andrewagain/3589bdbb51906c182a84 to your computer and use it in GitHub Desktop.
JSX Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** @jsx createNode */ | |
function createNode(tagName, attrs, ...children) { | |
const node = attrs || {}; | |
node.name = tagName; | |
if (children && children.length > 0) { | |
node.children = children; | |
} | |
return node; | |
} | |
const layout = ( | |
<widget> | |
<row> | |
<elem key='#1'/> | |
<elem key='#2'/> | |
</row> | |
<elem key='#3'/> | |
</widget> | |
); | |
console.log(JSON.stringify(layout, null, 2)); | |
/* | |
Output: | |
{ | |
"name": "widget", | |
"children": [ | |
{ | |
"name": "row", | |
"children": [ | |
{ | |
"key": "#1", | |
"name": "elem" | |
}, | |
{ | |
"key": "#2", | |
"name": "elem" | |
} | |
] | |
}, | |
{ | |
"key": "#3", | |
"name": "elem" | |
} | |
] | |
} | |
*/ |
FYI this comment informs babble what method to use for converting JSX into objects: /** @jsx createNode */
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Run this with
babel-node jsx-example.js
. No other modules or dependencies are necessary because babel supports JSX.