Hi, could you help me with this one?
I have a LiveComponent named ListIngredients that displays a list of ingredients in a form of a table. For each ingredient there are buttons allowing for different actions depending on the use case. This LiveComponent is reused in a few LiveViews in different contexts, for example:
- LV that allows for CRUD operations on listed ingredients
- LV that allows for adding one of listed ingredients to the meal
I wonder what would be the best approach to reuse ListIngredients component so that those buttons could act differently depending on the parent LV requirements. For now, I simply send a function from parent LiveView to ListIngredients in assigns but maybe there are better ways to accomplish this kind of reusability?
ListIngredients example usage in a parent LV render function:
<%=
live_component(@socket, ListIngredients, [
ingredients: @ingredients,
fun1: &link_delete/2,
fun2: &link_edit(&1, &2, IngredientLive.Edit)
])
%>
ListIngredients Component (fragment of render function):
...
<div class="list">
<%= for ingredient <- @ingredients do %>
<div class="ingredient">
<div class="ingredient-details name">
<%= ingredient.name %>
</div>
...
<div class="ingredient-buttons">
<%= if Map.has_key?(assigns, :fun1) do @fun1.(@socket, ingredient.id) end %>
<%= if Map.has_key?(assigns, :fun2) do @fun2.(@socket, ingredient.id) end %>
</div>
</div>
<% end %>
...