With the ViewComponent gem, what files make up a component, and how do you render one from a Rails view?
answer
- a Ruby class plus a sidecar template
- subclass of ViewComponent::Base
- inputs arrive through initialize
- render(Component.new(...)) calls render_in
- generator lives under view_component:
basics
~10 sA 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# 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}"
endgo deeper
Know the class-plus-template pair, where the files live, the generator name, and render(AlertComponent.new(...)).
Explain render_in, why the template sees only the component's state, the before_render and render? hooks, and how helpers are reached.
Catch v3-to-v4 upgrade breakage, reused instances, and helpers called too early, and decide which widgets deserve components.
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.