Jeffrey Hicks

Jeffrey Hicks

Platform Eng @R360

09 - Phoenix crash course #9: Function components and HEEx

Learn how to build reusable function components with HEEx templates in Phoenix

By Daniel Bergholz • Aug 19, 2025

Learn how to build reusable function components with HEEx templates in Phoenix.

HEEx templates

  • HEEx templates in Phoenix act like JSX in React—special HTML with Elixir expressions, conditionals, and loops

Function components

  • Any function that accepts assigns and returns HEEx is a component
  • You define components by declaring a function (e.g., def product(assigns) do ... end), and use them in templates with a dot: .product name={name}

Props and prop validation

  • Pass variables (props) to components with named attributes
  • Props can have type and required constraints using @attr for basic compile-time checks

Interpolating variables

  • Interpolate variables in HEEx with <%= %> rather than JSX’s {}
  • Use @name shorthand for reading assigns inside HEEx templates/components

Conditionals and loops

  • Use Elixir’s if or the :if={} attribute in HEEx, e.g., <div :if={@show}>Content</div>
  • Loops: use for and :for={} attributes, e.g., <div :for={product <- @products}><%= product.name %></div>

Data flow

  • Assign data in controllers using assign and pipe to render
  • Mock data and pass relevant props or collections down to the views/components

Best practices & syntax

  • Prefer inline, concise syntax for conditionals (:if={}) and loops (:for={product <- @products})
  • Pattern match assigns in non-HEEx contexts (like JSON views)

Summary

This episode shows how Phoenix combines frontend-style components with Elixir safety and expressiveness, letting you build interactive UIs efficiently, React-style, but in Elixir.

Related

#phoenix-and-elixir #phoenix-crash-course #daniel-bergholz