Components

Components

Components let you split the UI into independent, reusable pieces, and think about each piece in isolation.

Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return Virtual DOM elements describing what should appear on the screen.


Component Functions

All components in .dom are Javascript functions:

const { div } = H;

function Welcome(props) {
  return div(`Hello ${props.name}`);
}

This function is a valid .dom component because it accepts a “props” object argument and returns a Virtual DOM element.

Rendering Components

We have previously seen that you can render HTML elements using the H function:

const elm = H("div", "Hello world");

You can use the same function to render components.

const elm = H(Welcome, {"name": "World"});
Note that you cannot use the deconstructuring accelerator with Components. You must always call H(Component) to render it.

The library will call-out to your component, passing down the props given and will collect the resulting VDom tree.

You can see this in action:

Y29uc3QgeyBkaXYgfSA9IEg7CgovLyBEZWZpbmUgdGhlIGNvbXBvbmVudApmdW5jdGlvbiBXZWxjb21lKHByb3BzKSB7CiAgcmV0dXJuIGRpdihgSGVsbG8gJHtwcm9wcy5uYW1lfWApOwp9CgovLyBSZW5kZXIgaXQgClIoCiAgSChXZWxjb21lLCB7JiMzNDtuYW1lJiMzNDs6ICYjMzQ7V29ybGQmIzM0O30pLCAKICBkb2N1bWVudC5ib2R5Cik7
Loading interactive example...

Composing Components

Components can refer to other components in their output. This lets us use the same component abstraction for any level of detail. A button, a form, a dialog, a screen: in a .dom app, all those are commonly expressed as components.

Y29uc3QgeyBkaXYgfSA9IEg7CgovLyBEZWZpbmUgdGhlIGNvbXBvbmVudApmdW5jdGlvbiBXZWxjb21lKHByb3BzKSB7CiAgcmV0dXJuIGRpdihgSGVsbG8gJHtwcm9wcy5uYW1lfWApOwp9CgovLyBEZWZpbmUgdGhlIGFwcApmdW5jdGlvbiBBcHAocHJvcHMpIHsKICByZXR1cm4gZGl2KAogICAgSChXZWxjb21lLCB7bmFtZTogJiMzNDtBbGljZSYjMzQ7fSksCiAgICBIKFdlbGNvbWUsIHtuYW1lOiAmIzM0O0JvYiYjMzQ7fSksCiAgICBIKFdlbGNvbWUsIHtuYW1lOiAmIzM0O0NoYXJsaW5lJiMzNDt9KQogICk7Cn0KCi8vIFJlbmRlciB0aGUgYXBwClIoCiAgSChBcHApLAogIGRvY3VtZW50LmJvZHkKKTs=
Loading interactive example...