Element DSL

Element DSL

Preactile provides a type-safe DSL for building HTML elements with props and events. Elements live on E, attributes and events on A.

Basic elements

All standard HTML elements are available as constructors:

import preactile.*

E.div(
  E.h1("Title"),
  E.p("A paragraph of text."),
  E.a(A.href("https://preactjs.com"), "Preact homepage"),
)

Attributes and props

Use attribute constructors from A to set element attributes:

import preactile.*

E.input(
  A.`type`("text"),
  A.placeholder("Enter your name..."),
  A.value(""),
)

Event handlers

Attach event listeners with typed callbacks:

import preactile.*

E.button(
  A.onClick(_ => println("Clicked!")),
  A.onMouseOver(_ => println("Hovered")),
  "Click me",
)

Conditional rendering

Use when for conditional content:

import preactile.*

def statusBadge(isActive: Boolean) = E.div(
  when(isActive)(E.span(A.`class`("active"), "Online")),
  when(!isActive)(E.span(A.`class`("offline"), "Offline")),
)

Live demo: elements, events, and conditionals

This component uses a checkbox input with an onChange handler to toggle state, then conditionally renders content using when:

import preactile.*

object App extends StatefulComponent[Unit, Boolean]:
  override def initialState(props: Unit): Boolean = false

  def render(props: Unit, state: Boolean, instance: Instance): VNode = E.div(
    A.`class`("element-dsl-demo"),
    E.h4("Element DSL demo"),
    E.input(
      A.`type`("checkbox"),
      A.checked(state),
      A.onChange(_ => instance.setState(!state)),
    ),
    E.span(" Enable feature"),
    when(state)(
      E.div(
        A.`class`("feature-enabled"),
        E.p("Feature is now enabled!"),
        E.a(A.href("#"), A.onClick(_ => ()), "Learn more"),
      )
    ),
  )
end App

This example runs in your browser; enable JavaScript to see it.

See the Examples page for the other live demos.