How to customize the LiveView components within Phoenix?

I’m pretty impressed by how LiveView works and what you get out of the box using mix phx.gen.live. But now I’m wondering how you can customize the components used in the generated code, like modal or form. I’d like to add some different CSS stylings or even adapt the html structure a bit. But I don’t want to write completely new components. Is this possible?

I’m not quite sure I follow. The generated code is 100% just regular files in your app that you can edit as much as you like. Individual built in helpers like <.form></form> just emit a single <form> tag, so if you want additional HTML elements you can simply put them inside as normal.

Can you provide an example of something concrete you’re not sure how to edit?

Ah, thanks for this hint. I just realized that the generated helpers.ex file contains the code/template for the modal. Also didn’t now that the form helper just emits the “form” tag.

When in doubt, check out the source, it’s often easier to read than you’d think: phoenix_live_view/helpers.ex at v0.17.6 · phoenixframework/phoenix_live_view · GitHub

It sometimes adds some hidden inputs as well, but basically it’s just a form block.

After digging a bit deeper, I’m still a bit confused. For example, I would like to use the Phoenix standard helper email_input in my login template, but add some CSS classes to the HTML tag. So I guess I have to find the definition of the email_input function in the framework right? Or is there any kind of override mechanism in place?

Any option you pass, which is not explicitly listed in the docs to do otherwise will just be used as an attribute on the resulting html tag: email_input(f, :email, class: "…")

1 Like

Ok, understood. What is best practice then, that I create my own helpers and call the Phoenix helpers from those with my additional options? I don’t want to set the same options over and over again in the template.

That’s one way to do it. With heex I’d suggest using function components to do that.

1 Like

Thanks for helping me with my first steps with LiveView :slight_smile: Now I’m facing an other problem: I’ve added some more helper functions to the generated live_helpers.ex module. This works fine and I can use those using <.name> syntax in my heex templates. But as soon as I create my own module my_helpers.ex I get a undefined function error. Do I have to register the my module somewhere to be recognized? Basically, I’ve just copied the structure of the live_helpers.ex module.

1 Like

If you want to use functions from a module you need to import or alias that module. If you want it to be available everywhere the other liveview helpers are, add the import MyApp.MyHelpers to the desired section of myapp_web.ex