ViewComponent reference
11 March 2022 (Updated 11 March 2022)
What is ViewComponent?
ViewComponent is a framework by GitHub for creating reusable, testable, and encapsulated view components in Rails. The idea is that you compose your UI from a library of components much like you would if building an app using mainly React components.
Benefits of ViewComponent
Easier to reuse and maintain
You compose your UI out of smaller components. Each component has its dependencies explicitly stated in its constructor. For example:
class MessageComponent < ViewComponent::Base
def initialize(name:)
@name = name
end
end
It’s obvious what a component needs to render. In contrast, ERB views abound with mystery guests and it’s difficult to know what its dependencies are.
Testing
When your UI is complex and contains lots of Ruby logic, you can benefit from extended unit testing.
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
Sources
Tagged:
Rails tooling
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment