stratigos
How to Add HTML Attributes to HEEx Elements?
Hello I am new to Phoenix and am coming back to Elixir after a ~4 year hiatus.
I would like to add HTML attributes to HEEx elements, and they seem to do nothing - the resulting HTML does not contain an attribute.
Specifically, Im trying to add id="something" to a <.list> element. The resulting <dl> does not have any attributes I add. I have had a difficult time finding information on this online, and am wondering if its not possible.
How can HTML attributes be added to these elements?
Marked As Solved
KP123
You’re talking about the core components located in your_project/lib/your_project_web/components/core_components.ex, specifically list/1 and table/1 correct? The docs aren’t online for core components because they exist in that file. The fix is what I stated above. Take <.list/> for example, the only prop it defines is a slot that takes a title string. If you want it to take an ID then you need to add an ID prop to the component like so attr :id, :string, required: true, then render it in the template: <dl id={@id} class="-my-4 divide-y divide-zinc-100">...</dl>
Also Liked
KP123
Components need to be explicit about their props. If you only need an ID field then add an :id prop to your component definition. If you want to accept any valid html attribute then you’re looking for :global attributes. Check out the docs here.
barkerja
If you’re using the table component that ships with the generated phoenix core components, then there is a row_id attribute that can take a function to generate an ID for each row (tr).
Example:
<.table id="users" rows={@users} row_id={fn row -> "row-#{row.id}" end}>
<:col :let={user} label="id"><%= user.id %></:col>
<:col :let={user} label="username"><%= user.username %></:col>
</.table>
If you look at the component, you can see how that is used:
<tr :for={row <- @rows} id={@row_id && @row_id.(row)} class="group hover:bg-zinc-50">
stratigos
Thank you so much!!! I did not see this file when the app was generated. Totally new to me. This makes much more sense now.
So yes, I was talking about this core components file.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #hex









