How install and use Petal Components with Phoenix 1.7?

I’m trying to use Petal Components with Phoenix 1.7. I followed the directions at https://petal.build/components#install_petal_components. After that, if I define a LiveView module like this:

defmodule IknowWeb.PetalTest do
  use IknowWeb, :live_view

  def render(assigns) do
    ~H"""
    <.button label="Button" to="/" />
    """
  end
end

I get the error:

(CompileError) function button/1 imported from both 
PetalComponents.Button and IknowWeb.CoreComponents, call is ambiguous

I can resolve the ambiguity by rewriting my render function like this:

def render(assigns) do
    ~H"""
    <PetalComponents.Button.button label="Button" to="/" />
    """
  end

I’m sure there is a better, less verbose way of doing this.

Any suggestions?

you can rename the button function in core_components.ex to button_core or whatever you like
and the <.button will render the petal component button as you like.

I thought about that. But if I use phx.new.live, I think it will generate code using core_component function components. If that is correct, renaming core component functions probably isn’t ideal.

Did you end up finding a solution that you were happy with? I’m looking at Primer, and Petal, and renaming the default core_componenets doesn’t excite me either.

I see 2 workarounds;
A) you only import the petal components you need, or leave out modal, button and table (those are the ones that have the same name in core_components). Then you could style them in core_components. The instructions for this are on this page.
B) you rename modal, button and table in core_components, and customize phx_gen_live and other generators to use the changed component names, so you can keep using the generators.

Also, check out using a smaller module name.

This puts all the component functions in a module called PC. So you can create a button like this: <PC.button label="Save" />

2 Likes