Idiomatic phoenix functional components with potentially nil attributes

What would you consider most idiomatic?

Option 1:

def component_1(%{atr1: atr1} = assigns) when atr1 != nil do
    ~H"this is <%= @atr1 %>"
end
  
def component_1(assigns), do: ~H""

In Heex:

<.component_1 atr1={@something_that_might_be_nil} />

Option 2:

def component_2(%{atr1: atr1} = assigns) do
    ~H"this is <%= @atr1 %>""
end

in Heex:

<%= if @something_that_might_be_nil != nil do %>
    <.component_2 atr1={@something_that_might_be_nil} />
<% end %>

What I’d do:

attr :attribute, :any, default: nil

def component_1(assigns) do
  ~H”””
  <span :if={@attribute}>…</span>
  “””
end

# usage

<.component_1 attribute={@maybe_nil} />

I tend to think that Option 2 is easier to reason about (plus I’ll throw in the new syntactic sugar).

<.my_component :if={not is_nil(@atrr) attr={@attr} />

The thinking is: If you handle the nil case inside the component, then you are assuming stuff about your business logic in what could be a purely html rendering function.

In first case, is harder to reason about the parent component’s rendering logic, as you’ll have to check all the children components to see if they render or not.

I like my components as dumb as possible.

1 Like

Totally agree, I am more of a fan of filtering data down the pipeline that writing defensive code for multiple cases.