-
Notifications
You must be signed in to change notification settings - Fork 0
JSX
JSX is an extension to JavaScript which enables you to use XML-like syntax in JavaScript. For example:
const heading = <h1>This is JSX.</h1>;
It is usually nice to write UIs in JSX. However, it is optional. In fact, all the JSX code will be converted into normal JavaScript function calls. For instance,
const paragraph = <p class="para">JSX</p>;
will be transformed into something like this: (assuming the JSX factory function is HUI
)
const paragraph = HUI("p", { class: "para" }, "JSX");
As introduced at the beginning, JSX just brings an XML-like syntax sugar to JavaScript, so its syntax is JavaScript+XML
in brief.
-
Any tag can be self-closed if it doesn't have child nodes.
const emptyContainer = <div class="container" />; const appWithoutChildren = <App foo="bar" />;
-
Expressions can be inserted by wrapping them with braces.
const dynamicParagraph = <p>Time: {Date.now()}</p>; const appWithConfig = <App config={{ debug: true }} />; const inputWithListener = <input oninput={(event) => { handleInput(event); }} />;
-
A tag name starting with an uppercase letter will be considered a custom identifier.
import MyComponent from "MyComponent"; const myComponent = <MyComponent />;
-
An attribute whose value is omitted will be set to
true
. So,const input = <input autofocus />;
is equal to
const input = <input autofocus={true} />;
JSX is just a syntax sugar and it can not be directly run in browsers like plain JavaScript, so you need to transpile your JSX code into plain JavaScript. There are many tools which can do this for you. Here are some examples:
Babel
is a compiler for next generation JavaScript. It can also transform JSX syntax with a plugin.
-
Install
Babel
. -
Install the JSX transformer:
npm i -D @babel/plugin-transform-react-jsx
-
Set your
.babelrc
like this:{ // ... "plugins": [ // ... [ "@babel/plugin-transform-react-jsx", { "pragma": "HUI", "pragmaFrag": "HUI.Fragment" } ], // ... ], // ... }
-
Use
Babel
to transform your code.
For more information about Babel
, see babeljs.io.
TypeScript
supports JSX out of the box.
-
Install
TypeScript
compiler. -
Set your
tsconfig.json
like this:{ // ... "compilerOptions": { // ... "jsx": "react", "jsxFactory": "HUI", // ... }, // ... }
-
Compile your
TypeScript
code.
For more information about TypeScript
, see www.typescriptlang.org.