Skip to main content

Event listeners

A fncmp.HandleFn can also be used as a callback function for an event listener.

main.go
func handleClick(ctx context.Context) fncmp.FnComponent {
///
}

FnComponent's WithEvents method is used to add event listeners to the component.

main.go
func HandleMainFn(ctx context.Context) fncmp.FnComponent {
button := fncmp.HTML("<button>Click me</button>")
fn := fncmp.NewFn(ctx, button).WithEvents(handleClick, fncmp.OnClick)
return fn
}

Now, when the button is clicked, the handleClick function will be called.

tip

fncmp supplies a set of OnEvent constants (such as fncmp.OnClick) to be used with the WithEvents method.

Return a greeting from the handleClick function. This will begin to demonstrate what is happening in the DOM.

main.go
func handleClick(ctx context.Context) fncmp.FnComponent {
greeting := fncmp.HTML("<h1>Hello, world!</h1>")
return fncmp.NewFn(ctx, greeting)
}

Run the project and go to http://localhost:8080

go run main.go

Now, when you click the button, the greeting will appear.

Output: