-
Notifications
You must be signed in to change notification settings - Fork 0
JSX
JSX is a syntax extension to JavaScript which enables you to write XML-like expressions in JavaScript such as <h1>I'm a JSX expression</h1>
.
JSX expressions are much like XML fragments:
const element = ( // Parentheses usually make your codes prettier.
<div>
<p>JSX tags may contain children.</p>
Props can be passed like this:
<div id="sidebar"></div>
You can also use the self closing form of a tag if there are no children:
<div id="sidebar" />
A custom component:
<CustomComponent>
Please note that the name of a custom component must starts with
a capitalized letter, or it will be treated as a built-in tag.
</CustomComponent>
JavaScript values can be mixed in by wrapping them with brackets:
{'For instance,'} 6 + 6 = {6 + 6}.
</div>
);
JSX
is really awesome, but you need to use a compiler to convert it into plain JavaScript to let it run in browsers.
babel
is a JavaScript compiler which can do this for you.
To use babel
to compile JSX, you need a JSX transformer first:
npm i -D babel-plugin-transform-react-jsx
Then, set your .babelrc
like this:
{
"plugins": [
[
"transform-react",
{
"pragma": "HEle.createElement",
"pragmaFrag": "HEle.Fragment"
}
]
]
}
For more information about babel
, see babeljs.io.
TypeScript
supports JSX
out of the box.
You need to set some settings in the tsconfig.json
like this:
{
"compilerOptions": {
"jsx": "react",
"jsxFactory": "HEle.createElement",
}
}
For more information about TypeScript
, see www.typescriptlang.org.
In fact, the compilers just convert JSX expressions into function calls.
For example,
<h1 id="title">Hello, world!</h1>
will be compiled to:
HEle.createElement('h1', { id: 'title' }, 'Hello, world!');
So, you can also use hele
without JSX:
// Use a shortcut may bring much convenience.
const h = HEle.createElement;
HEle.render(
h(
'h1',
null,
'Hello, ',
h(
MyComponent,
{
color: 'blue'
},
'world'
),
'!'
),
document.getElementById('root')
);