ViewComponent (v3.11.0)

A framework for creating reusable, testable & encapsulated view components, built to integrate seamlessly with Ruby on Rails.

What’s a ViewComponent?

Think of ViewComponents as an evolution of the presenter pattern, inspired by React. A ViewComponent is a Ruby object:

class MessageComponent < ViewComponent::Base
  erb_template <<-ERB
    <h1>Hello, <%= @name %>!</h1>
  ERB

  def initialize(name:)
    @name = name
  end
end

Which is instantiated and passed to Rails’ #render:

<%= render(MessageComponent.new(name: "World")) %>

Returning markup:

<h1>Hello, World!</h1>

Why use ViewComponents?

TL;DR

ViewComponents work best for templates that are reused or benefit from being tested directly. Partials and templates with significant amounts of embedded Ruby often make good ViewComponents.

Single responsibility

Rails applications often scatter view-related logic across models, controllers, and helpers, diluting their intended responsibilities. ViewComponents consolidate the logic needed for a template into a single class, resulting in a cohesive object that is easy to understand.

ViewComponent methods are implemented within the scope of the template, encapsulating them in proper object-oriented fashion. This cohesion is especially evident when multiple methods are needed for a single view.

Testing

ViewComponent was designed with the intention that all components should be unit tested. In the GitHub codebase, ViewComponent unit tests are over 100x faster than similar controller tests.

With ViewComponent, integration tests can be reserved for end-to-end assertions, with permutations covered at the unit level.

For example, to test the MessageComponent above:

class MessageComponentTest < GitHub::TestCase
  include ViewComponent::TestHelpers

  test "renders message" do
    render_inline(MessageComponent.new(name: "World"))

    assert_selector "h1", text: "Hello, World!"
  end
end

ViewComponent unit tests leverage the Capybara matchers library, allowing for complex assertions traditionally reserved for controller and browser tests.

Data Flow

Traditional Rails templates have an implicit interface, making it hard to reason about their dependencies. This can lead to subtle bugs when rendering the same template in different contexts.

ViewComponents use a standard Ruby initializer that clearly defines what’s needed to render, making reuse easier and safer than partials.

Performance

Based on several benchmarks, ViewComponents are ~10x faster than partials in real-world use-cases.

The primary optimization is pre-compiling all ViewComponent templates at application boot, instead of at runtime like traditional Rails views.

For example, the MessageComponent template is compiled onto the Ruby object:

# app/components/message_component.rb
class MessageComponent < ViewComponent::Base
  def initialize(name:)
    @name = name
  end

  def call
    @output_buffer.safe_append = "<h1>Hello, ".freeze
    @output_buffer.append = (@name)
    @output_buffer.safe_append = "!</h1>".freeze
    @output_buffer.to_s
  end
end

Code quality

Template code often fails basic Ruby standards: long methods, deep conditional nesting, and mystery guests abound.

ViewComponents are Ruby objects, making it easy to follow (and enforce) code quality standards.

Contributors

ViewComponent is built by over a hundred members of the community, including:

nickcoyne nachiket87 andrewjtait asgerb bbugh bigbigdoudou blakewilliams boardfish bobmaerten bpo bradparker cesariouy cover cpjmcquillan crookedgrin czj dani-sc danieldiekmeier danielnc dark-panda davekaro dixpac dukex dylanatsmith dylnclrk edwinthinks elia franco franks921 franzliedke fsateler fugufish g13ydson horacio horiaradu yykamei jaredcwhite jasonswett javierm jcoyne jensljungblad joelhawksley johannesengl jonspalmer juanmanuelramallo jules2689 jwshuff kaspermeyer kylefox kdonovan leighhalliday llenk manuelpuyol matheusrich Matt-Yorkley mattbrictson mattwr18 maxbeizer mellowfish metade michaelem mixergtz mrrooijen nashby nicolas-brousse nshki nshki patrickarnett rainerborene rdavid1099 richardmarbach rmacklin ryogift sammyhenningsson sampart seanpdoyle simonrand skryukov smashwilson spdawson Spone stiig swanson tbroad-ramsey tclem tenderlove tgaff thutterer tonkpils traels vinistock wdrexler websebdev xkraty xronos-i-am yykamei matheuspolicamilo danigonza erinnachen ihollander svetlins nickmalcolm reeganviljoen thomascchen milk1000cc aduth htcarr3

Who uses ViewComponent?

Using ViewComponent? Send a pull request to update this list! You can also check out how various projects use ViewComponent.


Getting started →