Import multiple Phoenix Components for use in LiveView

Hi Elixir/Phoenix Community :smiling_face_with_three_hearts:

Since I’ve learnt about Phoenix.Component, I have created few components to be used in LiveView such as CardComponent, TableComponent and etc.

Why

I am using Tailwindcss + DaisyUI for all the styling. I use the CardComponent like

<.card>
    card content
</.card>

in LiveView, so in case I want to change the card styling, I only change it in CardComponent only.

Questions

  1. Is this a good practice?
    Phoenix has Phoenix.Component and even tailwindcss recommended us to. But I am new to Elixir and Phoenix, is the the case?

  2. How to import multiple components/Helpers?

    • Since I have created many components, and some components are widely use, I would like to import these components and make it available globally just like the <.modal></modal> in live_helpers.ex when we created phoenix app.
    • I know I can import TestWeb.CardComponent inside test_web.ex and maybe import all other components as well. This is messy right?
    • I would like to use the existing live_helpers.ex to import common components and make them available for all liveview. But how??
    • I have created many components in text_web/components/xxx_component.ex. For maintainability, one component one file, instead of put all of them into live_helpers.ex

The mentioned approach in 2. is what came up to my brain base on my existing experience and it might not be the final or correct approach. If you have better idea, it would be GREAT!

Extra

I just realize DailyUI + LiveView.JS is very powerful! DaisyUI doesn’t require javascript (example dropdown) and I can use LiveView.JS to add_class to make it dropdown. no AlpineJS required for basic use cases :smiling_face_with_three_hearts:

1 Like

yes

you could update your test_web.ex to import them. You already have this defined. just add the import there and it will import it in all your LiveView modules

def live_view do
  quote do
    use Phoenix.LiveView,
      layout: {PlexusWeb.LayoutView, "live.html"}

    import TestWeb.CardComponent

    unquote(view_helpers())
  end
end

The code above is called when you do use TestWeb, :live_view.

now everywhere you use liveview you would have it available. You would still need to add each component file import here. but atleast it is only one place

2 Likes