skip to content

ViewComponent & Phlex

ViewComponent and Phlex replace partials with Ruby classes: sidecar templates or pure-Ruby markup, slots, and unit tests via render_inline. Interviewers ask when a component beats a partial.

part ofRuby on Railsread it →
on this pageshow

explore

questions

5

With the ViewComponent gem, what files make up a component, and how do you render one from a Rails view?

level: juniorimportance: must knowfreq 32%

answer

  1. a Ruby class plus a sidecar template
  2. subclass of ViewComponent::Base
  3. inputs arrive through initialize
  4. render(Component.new(...)) calls render_in
  5. generator lives under view_component:

basics

~10 s

A ViewComponent is a Ruby class inheriting from ViewComponent::Base, usually app/components/alert_component.rb, with a sidecar template beside it, alert_component.html.erb. A view renders it with render(AlertComponent.new(kind: :warning, message: "...")).

solid answer

~40 s

`bin/rails generate view_component:component Alert kind message` writes `app/components/alert_component.rb`, a class inheriting from `ApplicationComponent` if the app defines one, else `ViewComponent::Base`, with `def initialize(kind:, message:)`; a sidecar template `app/components/alert_component.html.erb`; and `test/components/alert_component_test.rb`. The template runs in the component instance, so it sees the component's instance variables and methods and none of the controller's instance variables. A view or controller calls `render(AlertComponent.new(kind: :warning, message: "Upload the police report"))`; Rails' `render` sees an object responding to `render_in` and hands it the view context. A block passed to `render` becomes `content`, `render?` returning false skips output, and `before_render` is the first point where `helpers` works. In ViewComponent 4 the generator is namespaced (`rails g component` is gone), and an instance renders once: a second render raises `ViewComponent::ReusedInstanceError`.

code

ruby · 15 lines
ruby
# app/components/alert_component.rb
class AlertComponent < ViewComponent::Base
  def initialize(kind:, message:)
    @kind = kind
    @message = message
  end

  def render?
    @message.present?
  end

  private

  def css_class = "alert alert--#{@kind}"
end

go deeper

for a junior

Know the class-plus-template pair, where the files live, the generator name, and render(AlertComponent.new(...)).

for a middle

Explain render_in, why the template sees only the component's state, the before_render and render? hooks, and how helpers are reached.

for a senior

Catch v3-to-v4 upgrade breakage, reused instances, and helpers called too early, and decide which widgets deserve components.

for a principal

Decide whether the app standardises on components for shared UI, and what the convention for inputs, naming and folders is.

## What a component is An insurance-claims portal shows the same **alert box** on many pages: a missing document, a rejected payment, a claim approved. As a partial it would read whatever locals and instance variables happen to be around. With the **ViewComponent** gem it becomes a Ruby object with explicit inputs and its own template. The generator shows the anatomy: ```bash bin/rails generate view_component:component Alert kind message ``` which writes: 1. `app/components/alert_component.rb` - the **class**, inheriting from `ApplicationComponent` when the app defines one, otherwise from `ViewComponent::Base`; 2. `app/components/alert_component.html.erb` - the **sidecar template**, found by name next to the class; 3. `test/components/alert_component_test.rb` - a unit test (or a spec, with RSpec configured). Options add more: `--preview` writes a preview class, `--sidecar` puts the template in an `alert_component/` folder, `--inline` puts the template in the class, and `--call` generates a `call` method instead of a template. ## The class and its template ```ruby class AlertComponent < ViewComponent::Base def initialize(kind:, message:) @kind = kind @message = message end def css_class = "alert alert--#{@kind}" end ``` ```erb <div class="<%= css_class %>" role="alert"><%= @message %></div> ``` The template is compiled into a method on the class, so inside it `self` is the component: - it sees the component's **instance variables** and **methods** (`@message`, `css_class`); - it does **not** see the controller's instance variables; `@claim` is `nil` there unless passed in; - Action View's own helpers (`link_to`, `tag`, `number_to_currency`) are available because `ViewComponent::Base` includes them; the app's helpers in `app/helpers` are reached through `helpers.claim_status_label(...)` or by including the module. ## Rendering it From any template, or from a controller action: ```erb <%= render(AlertComponent.new(kind: :warning, message: "Upload the police report")) %> ``` Rails' `render` checks whether its argument responds to **`render_in`**. ViewComponent implements that method, so Rails passes the current view context and inserts the returned HTML. Missing keyword arguments fail early with Ruby's `ArgumentError`, before any HTML is produced. ## Lifecycle hooks worth knowing | Hook | When it runs | Typical use | |---|---|---| | `initialize` | when you call `new` | store inputs; no view context yet | | `before_render` | after the view context is attached | read helpers, the request or `controller` | | `render?` | before the template | return `false` to render nothing | | `content` | when the template reads it | the block passed to `render` | Calling `helpers` inside `initialize` raises `ViewComponent::HelpersCalledBeforeRenderError`, because no view context exists yet. ## ViewComponent 4 details that trip upgrades - The generator moved to the `view_component:` namespace; the old `rails g component` is gone. - `ViewComponent::Base` no longer defines a catch-all initializer, so a component without its own `initialize` takes no arguments. - Since **4.14** an instance is **single-use**: rendering the same object twice raises `ViewComponent::ReusedInstanceError`, because state from the first render could leak into the second. Build a new instance per render; for lists, `with_collection` builds a fresh instance per item, passing it under a keyword named after the component (`alert:` for `AlertComponent`). - Preview and generator settings now live under `config.view_component.previews.*` and `config.view_component.generate.*`. ## Mistakes interviewers listen for | Belief | What ViewComponent actually does | |---|---| | the template can read `@claim` from the controller | it sees only the component's own state; pass the claim in | | components render with `render partial:` | they render as objects through `render_in` | | `rails g component` is the generator | in v4 it is `view_component:component` | | one instance can be reused for every row | since 4.14 a second render raises | | `helpers` works anywhere in the class | only once rendering has started, from `before_render` on | A junior answer that names the two files, the base class and the `render(...new(...))` call is enough to open the topic; the follow-ups usually probe the instance-variable boundary, because that is the property that makes a component different from a partial.

  • Why does @claim come out nil inside a component template when the controller set it?
    The template runs as a method on the component instance, so instance variables resolve on the component, not on the view or controller. Pass the claim in through `initialize` (for example `ClaimCardComponent.new(claim: @claim)`); that explicit input is the point of the component.
  • How do you call an app helper such as claim_status_label from inside a component?
    Use the `helpers` proxy, `helpers.claim_status_label(@claim)`, from `before_render` or the template, or include the helper module in the component. Calling `helpers` in `initialize` raises `HelpersCalledBeforeRenderError`, because the view context is attached only when rendering starts.

  • A component template can read the controller's instance variables
  • Components are rendered with render partial: "components/alert"
  • rails g component Alert is the ViewComponent 4 generator
  • You can build one AlertComponent instance and render it on every row
  • helpers is safe to call inside initialize

Assumes ViewComponent 4.15 on Rails 8.1: the generator is view_component:component since 4.0, and since 4.14 rendering one instance twice raises ViewComponent::ReusedInstanceError.

open as a page

In ViewComponent, how do renders_one and renders_many give a card component header and action regions, and how does a caller fill them?

level: middleimportance: should knowfreq 28%

basics

~20 s

renders_one :header and renders_many :actions declare named regions. The caller fills them inside the render block with card.with_header { ... } and card.with_action(...), and the template prints header, iterates actions, checks header? and prints content for the body.

open as a page

In a Rails app, when does a ViewComponent or Phlex component beat a partial, and what does adopting components cost the team?

level: seniorimportance: should knowfreq 34%

basics

~20 s

A component beats a partial for reused UI with logic or variants: inputs are explicit, logic lives in testable methods, and render_inline tests run without a browser. The cost is another dependency and convention, helpers reached explicitly, and single-use instances.

open as a page

How do you unit-test a ViewComponent with render_inline, and what do ViewComponent previews add beyond those tests?

level: seniorimportance: should knowfreq 24%

basics

~20 s

render_inline(AlertComponent.new(...)) renders the component through a test controller's view context, returns a Nokogiri fragment and sets page for Capybara assertions, with no browser or routing. Previews render the same components at /rails/view_components in development for visual review.

open as a page

In Phlex 2 with phlex-rails, how does a Phlex::HTML component produce markup, and how does it call Rails helpers such as link_to?

level: middleimportance: nice to knowfreq 14%

basics

~20 s

A Phlex component is a Ruby class inheriting from Phlex::HTML whose view_template method calls element methods such as div and p with blocks; output is escaped by default. Rails helpers are included as phlex-rails adapters, e.g. include Phlex::Rails::Helpers::LinkTo.

open as a page