T templcn/ui
Componentsonner

Sonner

An opinionated toast component for Go and templ.

Preview

An opinionated toast component for Go and templ.

Installation

Add this component to your project using the CLI.

templcn add sonner

Usage

1. Import the component in your Go or templ file:

import "your-module/ui"

2. Use the component in your template:

// 1. Add Toaster to your root layout:
@ui.Toaster(ui.ToasterProps{})

// 2. Trigger toasts with a button or script:
@ui.Button(ui.ButtonProps{
  Variant: ui.ButtonVariantOutline,
  DOMProps: ui.DOMProps{
    Attrs: templ.Attributes{
      "onclick": "toast('Event has been created', { description: 'Sunday, December 03, 2023 at 9:00 AM', action: { label: 'Undo', onClick: () => console.log('Undo') } })",
    },
  },
}) {
  Show Toast
}

Composition

Use these parts together to build the component.

Toaster
├── Button

Examples

Named examples and common variations.

Default

A default toast with title and description.

Success

A success toast with green accent.

Error

A destructive error toast.

Action

A toast with an action button.

API Reference
PropTypeDefaultDescription
Themestring""Force light or dark mode.
Positionstring"bottom-right"Toast position on screen.
RichColorsboolfalseEnable rich status colors.
View source
package ui

import (
	"context"
	"io"

	"github.com/a-h/templ"
)

type ToasterProps struct {
	DOMProps
	Theme      string
	Position   string
	RichColors bool
	Duration   int
}

func Toaster(props ToasterProps) templ.Component {
	return templ.ComponentFunc(func(ctx context.Context, w io.Writer) error {
		attrs := attrsFromDOMProps(props.DOMProps, "toaster", "fixed inset-0 z-50")
		if props.Theme != "" {
			attrs["data-theme"] = props.Theme
		}
		if props.Position != "" {
			attrs["data-position"] = props.Position
		}
		if props.RichColors {
			attrs["data-rich-colors"] = "true"
		}
		if props.Duration > 0 {
			attrs["data-duration"] = props.Duration
		}
		return renderElement(ctx, w, "div", attrs, templ.GetChildren(ctx))
	})
}