I found the idea of implementing components in Go to make it easier to use Tailwind CSS really neat. I always disliked that you needed Javascript (React for example) to do something like this, even though I'm a big fan of working component-based when creating a website.

I played with a similar idea in the past, but never got as far as I liked. Markus however got quite a bit further than I did. With the use of his gomponents module, defining a component called NiceButton becomes as easy as:

import (
    g "github.com/maragudk/gomponents"
    c "github.com/maragudk/gomponents/components"
    . "github.com/maragudk/gomponents/html"
)

func NiceButton(text string, primary bool) g.Node {
    return Button(g.Text(text), c.Classes{
        "flex items-center justify-center px-4 py-3 rounded-md": true,
        "text-white bg-indigo-600 hover:bg-indigo-700":          primary,
        "text-indigo-600 bg-gray-50 hover:bg-gray-200":          !primary,
    })
}

You can then use this button everywhere:

import (
    g "github.com/maragudk/gomponents"
    c "github.com/maragudk/gomponents/components"
    . "github.com/maragudk/gomponents/html"
)

func Home() g.Node {
    return Div(Class("max-w-lg flex space-x-8"),
    NiceButton("I'm primary", true),
    NiceButton("I'm just secondary", false),
    )
}

You can find a more complete sample here. This is something I'll definitely try out in the future…

Related Posts

  • Handling Unix timestamps in JSON
  • Combining channels and wait groups
  • Pretty-print JSON with Go
  • Using the Docker client from Go part 2
  • Using environment variables in Go tests