Function Components

The concept of component is not native to this library. However, because it is powerful, you can mimic the component pattern. This is all due to how the functions are treated in the template.

Let's define a component as a function that returns something to be rendered and might or might not take an input to help with what needs to be rendered.

With that definition, we can create a simple component like so:

const Button = ({
  content = "", 
  disabled = false, 
  type = "button"
}) => {
  return html`
    <button 
      type="${type}"
      disabled="${disabled}"
      >
      ${content}
    </button>`;
}

To use it, simply call it as a function. This can happen directly in the template or outside in a variable:

html`${Button({content: 'click me'})}`

Because you have a function, you can put all the logic related to the component inside. This pattern allows you to reuse template anywhere with flexibility the inputs give you.

In addition, you can consider passing state around as props. This will allow you to affect the template directly when there is a change.

const TextInput = ({value = "", onChange} = "") => {
  return html`
    <input 
      type="text" 
      value="${value}" 
      onchange="${e => onChange?.(e.target.value)}"
      />
  `
}

const [name, updateName] = state("")

html`${TextInput({value: name, onChange: updateName})}`