Skip to content

Components

Maxence Charriere edited this page Feb 27, 2020 · 15 revisions

Table of Contents

Description

Components are structs that let you split the UI into independent and reusable pieces.

Here is a component example that shows a hello world:

type hello struct {
    app.Compo
    name string
}

func (h *hello) Render() app.UI {
    return app.Div().Body(
        app.H1().Body(
            app.Text("Hello "),
            app.Text(h.name),
        ),
        app.Input().
            Value(h.name).
            OnChange(h.OnInputChange),
    )
}

func (h *hello) OnInputChange(src app.Value, e app.Event) {
    h.name = src.Get("value").String()
    h.Update()
}

Create

Creating a component is done by embedding app.Compo into a struct:

type hello struct {
    app.Compo   // <-- The base component implementation
    name string
}

Customize

Once created, the next thing to do is define the component appearance. This is done by implementing the Render() method:

func (h *hello) Render() app.UI {
    return app.Div().Body(
        app.H1().Body(
            app.Text("Hello "),
            app.Text(h.name),
        ),
        app.Input().
            Value(h.name).
            OnChange(h.OnInputChange),
    )
}

It returns an app.UI element that can be either an HTML element or another component.

See the Declarative Syntax topic to get more info about how to shape a component.

Update

The Render() method defines the component appearance.

In the hello world example above, the rendering uses the name component field to define the title and the input default value.

It also set up an event handler that is called when the input change:

func (h *hello) OnInputChange(src app.Value, e app.Event) {
    h.name = src.Get("value").String()
    h.Update()
}

At each change, the input value is assigned the component name field.

The way to tell the browser that the component appearance has to be updated is by calling the Compo.Update() method:

h.Update()

Under the hood, the update method creates a new state that is compared to the current one. It then performs a diff and updates only the HTML nodes where differences are found.

Composing Components

Lifecycle

OnMount

OnNav

OnDismount

Clone this wiki locally