Skip to content
Merged
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 111 additions & 8 deletions docs/jsx.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ Explanation, examples, and build notes on how to use JSX in your Mithril.js-base
# JSX

- [Description](#description)
- [Setup](#setup)
- [Setup JSX](#setup-jsx)
- [Production build](#production-build)
- [Using Babel with Webpack](#using-babel-with-webpack)
- [Setup TSX](#setup-tsx-jsx-in-typescript)
- [Using Closure Components in TSX](#using-closure-components-in-tsx)
- [Differences with React](#differences-with-react)
- [JSX vs hyperscript](#jsx-vs-hyperscript)
- [Tips and Tricks](#tips-and-tricks)
Expand Down Expand Up @@ -58,9 +60,9 @@ m.render(document.body, <MyComponent />)

---

### Setup
### Setup JSX

The simplest way to use JSX is via a [Babel](https://babeljs.io/) plugin.
When using JavaScript, the simplest way to use JSX is via a [Babel](https://babeljs.io/) plugin. (For TypeScript follow the [instructions below](#setup-tsx-jsx-in-typescript)).

Babel requires npm, which is automatically installed when you install [Node.js](https://nodejs.org/en/). Once npm is installed, create a project folder and run this command:

Expand Down Expand Up @@ -241,21 +243,122 @@ See [the Webpack docs](https://webpack.js.org/plugins/provide-plugin/) for more

---

### Setup TSX (JSX in TypeScript)

When using [TypeScript](https://www.typescriptlang.org/), all you need to do is tell TypeScript how to handle JSX code correctly. Since TypeScript can transpile JSX and TSX on its own, you don't need any other tools like Babel to do it for you. (More information can be found about JSX in TypeScript [here](https://www.typescriptlang.org/docs/handbook/jsx.html).)

Add `jsx` and `jsxFactory` to `compilerOptions` in your `tsconfig.json`:

```json
{
"compilerOptions": {
"jsx": "react",
"jsxFactory": "m",
"jsxFragmentFactory": "m.Fragment"
}
}
```

This setup should be enough to get most JSX functionality working.

#### Using closure components in TSX
>Because of https://github.com/microsoft/TypeScript/issues/21699, we advise against using [closure components](components.md#closure-component-state) in TypeScript for now. Either use [class components](components.md#class-component-state) without attribute inspection or Hyperscript instead (see the list of alternatives below the code example).
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion to clean this up and elaborate on the recommendation better. Also, we usually keep spaces after Markdown block-level syntax like > and #, and this suggestiin factors that in.

If there's anything you feel is unclear or you disagree with, feel free to comment here on it.

Suggested change
>Because of https://github.com/microsoft/TypeScript/issues/21699, we advise against using [closure components](components.md#closure-component-state) in TypeScript for now. Either use [class components](components.md#class-component-state) without attribute inspection or Hyperscript instead (see the list of alternatives below the code example).
> Because [TypeScript does not, at the time of writing, allow customizing the type used to check JSX component validity](https://github.com/microsoft/TypeScript/issues/21699), we recommend you avoid using [closure components](components.md#closure-component-state) as JSX component names in TypeScript for now. Either use [class components](components.md#class-component-state) exclusively or use [hyperscript](hyperscript.md) to construct them.
>
> You'll see what we mean after reading this section. It's not simple to work around TypeScript's missing feature here.

Copy link
Contributor Author

@JodliDev JodliDev Aug 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do agree with that change but not with your last addition ("You'll see what we mean after reading this section. It's not simple to work around TypeScript's missing feature here").
The actual workaround are only 3 lines of code and its usage is almost identical to normal closure components. I have been working with it for a while now and find it a lot more convenient than using class components.

We might also want to point out that class compoments dont fully work in TSX either (attribute inspection is broken).

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do agree with that change but not with your last addition ("You'll see what we mean after reading this section. It's not simple to work around TypeScript's missing feature here").

The actual workaround are only 3 lines of code and its usage is almost identical to normal closure components. I have been working with it for a while now and find it a lot more convenient than using class components.

That's fair. I'd need some more time to think about it. How does ripping out this entire block quote and filing a follow-up issue in this repo sound?

We might also want to point out that class compoments dont fully work in TSX either (attribute inspection is broken).

Good catch. Honestly, I'm convinced the attribute inspection problem may be more of an issue with the current types. Might be better to just file a tracking issue in Mithril core about this. (I've almost moved the types back into Mithril core I don't know how many times by now, because it's just easier to make sure it tracks changes correctly here.)

And if we integrate that here, we could look into what's truly necessary to make Mithril play nice with TypeScript. (I'm leaning towards maybe a @m.component decorator that just magically fixes up all the types. JS can continue to be free-form, and TS users can benefit from the static annotation.)


TypeScript only expects an attribute object as a parameter. But Mithril.js provides a `Vnode` object instead. This leads to the editor showing faulty parameters even though the JSX would compile correctly. If you want to use closure components in TypeScript, you need to trick the TypeScript error checking.


For example, if you try to compile this code:

```typescript jsx
interface Attributes {
greet: string
}
function ChildComponent(vNode: Vnode<Attributes>): m.Component<Attributes> {
return {
view: <div>{vNode.attrs.greet}</div>
};
}

function ParentComponent() {
return {
view: <div><ChildComponent greet="Hello World"/></div> //This line will compile correctly but shows the errors bellow
};
}
```

TypeScript will report this error:

```
TS2739: Type { greet: string; } is missing the following properties from type Vnode<{}, {}>: tag, attrs, state
TS2786: LoadingSpinner cannot be used as a JSX component.
```

There are several options to circumvent that problem:
1. Instead of `<div><ChildComponent greet="Hello World"/></div>`, use `<div>{m(ChildComponent, {greet: "Hello World"})}</div>` instead.
2. Use [class components](components.md#class-component-state) instead. Class components will not show any errors. But TypeScript will not be able to autocomplete or inspect attributes (in this example `greet` would be unknown when used in `ParentComponent`).
3. Create a "translation function" (see `TsClosureComponent()` in the example below) to trick TypeScript.

The following code will work without errors:

```typescript jsx
/**
* Use TsClosureComponent to create closure components that can be inspected by TypeScript.
*/
export function TsClosureComponent<T>(create: Mithril.ClosureComponent<T>) {
return create as any as (
(attrs: T & Mithril.CommonAttributes<T, unknown>) => JSX.Element
)
}


interface Attributes {
greet: string
}
// We slightly altered the definition of `ChildComponent` by using `TsClosureComponent`
const ChildComponent = TsClosureComponent<Attributes>(vNode => {
return {
view: () => <div>{vNode.attrs.greet}</div>
};
})

function ParentComponent() {
return {
view: () => <div><ChildComponent greet="Hello World"/></div>
};
}

```

When you need generics for your closure component, you can use the following definition style:

```typescript jsx
function ChildComponentImpl<T>() {
// ...
}

const ChildComponent = TsClosureComponent(ChildComponentImpl); //for TsClosureComponent, see above

const jsx = <div>
<ChildComponent<SomeClass> />
</div>
```


### Differences with React

JSX in Mithril has some subtle but important differences compared to React's JSX.
JSX in Mithril.js has some subtle but important differences compared to React's JSX.

#### Attribute and style property case conventions

React requires you use the camel-cased DOM property names instead of HTML attribute names for all attributes other than `data-*` and `aria-*` attributes. For example using `className` instead of `class` and `htmlFor` instead of `for`. In Mithril, it's more idiomatic to use the lowercase HTML attribute names instead. Mithril always falls back to setting attributes if a property doesn't exist which aligns more intuitively with HTML. Note that in most cases, the DOM property and HTML attribute names are either the same or very similar. For example `value`/`checked` for inputs and the `tabindex` global attribute vs the `elem.tabIndex` property on HTML elements. Very rarely do they differ beyond case: the `elem.className` property for the `class` attribute or the `elem.htmlFor` property for the `for` attribute are among the few exceptions.
React requires you use the camel-cased DOM property names instead of HTML attribute names for all attributes other than `data-*` and `aria-*` attributes. For example using `className` instead of `class` and `htmlFor` instead of `for`. In Mithril.js, it's more idiomatic to use the lowercase HTML attribute names instead. Mithril.js always falls back to setting attributes if a property doesn't exist which aligns more intuitively with HTML. Note that in most cases, the DOM property and HTML attribute names are either the same or very similar. For example `value`/`checked` for inputs and the `tabindex` global attribute vs the `elem.tabIndex` property on HTML elements. Very rarely do they differ beyond case: the `elem.className` property for the `class` attribute or the `elem.htmlFor` property for the `for` attribute are among the few exceptions.

Similarly, React always uses the camel-cased style property names exposed in the DOM via properties of `elem.style` (like `cssHeight` and `backgroundColor`). Mithril supports both that and the kebab-cased CSS property names (like `height` and `background-color`) and idiomatically prefers the latter. Only `cssHeight`, `cssFloat`, and vendor-prefixed properties differ in more than case.
Similarly, React always uses the camel-cased style property names exposed in the DOM via properties of `elem.style` (like `cssHeight` and `backgroundColor`). Mithril.js supports both that and the kebab-cased CSS property names (like `height` and `background-color`) and idiomatically prefers the latter. Only `cssHeight`, `cssFloat`, and vendor-prefixed properties differ in more than case.

#### DOM events

React upper-cases the first character of all event handlers: `onClick` listens for `click` events and `onSubmit` for `submit` events. Some are further altered as they're multiple words concatenated together. For instance, `onMouseMove` listens for `mousemove` events. Mithril does not do this case mapping but instead just prepends `on` to the native event, so you'd add listeners for `onclick` and `onmousemove` to listen to those two events respectively. This corresponds much more closely to HTML's naming scheme and is much more intuitive if you come from an HTML or vanilla DOM background.
React upper-cases the first character of all event handlers: `onClick` listens for `click` events and `onSubmit` for `submit` events. Some are further altered as they're multiple words concatenated together. For instance, `onMouseMove` listens for `mousemove` events. Mithril.js does not do this case mapping but instead just prepends `on` to the native event, so you'd add listeners for `onclick` and `onmousemove` to listen to those two events respectively. This corresponds much more closely to HTML's naming scheme and is much more intuitive if you come from an HTML or vanilla DOM background.

React supports scheduling event listeners during the capture phase (in the first pass, out to in, as opposed to the default bubble phase going in to out in the second pass) by appending `Capture` to that event. Mithril currently lacks such functionality, but it could gain this in the future. If this is necessary you can manually add and remove your own listeners in [lifecycle hooks](lifecycle-methods.md).
React supports scheduling event listeners during the capture phase (in the first pass, out to in, as opposed to the default bubble phase going in to out in the second pass) by appending `Capture` to that event. Mithril.js currently lacks such functionality, but it could gain this in the future. If this is necessary you can manually add and remove your own listeners in [lifecycle hooks](lifecycle-methods.md).

---

Expand Down