Views grow. The same card, button or navigation shows up on ten screens, and soon the same twelve lines of HTML live in ten places. Rails partials are the first tool against this; ViewComponent is the second, for components that carry logic, helpers, CSS and JavaScript of their own. This card teaches you to give your views a small, readable vocabulary of components.
Important
Work on this lesson in
advisormode.
Learning goals
- You can explain how a partial exposes an API to its callers: through locals, and by accepting a block that the partial yields.
- You can explain the benefits of a view component over a partial: it hides HTML details behind an explicit interface and co-locates the template with its helpers, its JavaScript and its CSS.
- You can decide when a piece of view code deserves extraction at all, and whether a partial, a helper or a component is the right form.
- You can extract recurring HTML into partials and helpers so that views read as a terse description of the screen.
- You can build a ViewComponent following our conventions, and write a unit test for it.
Resources
Read what's new to you, skim what's familiar, skip what you already master. Stop when you can meet the learning goals.
Your agent can also generate an overview, a tutorial or an explanation for anything here, tailored to what you already know. Just ask.
Partials
- 📄 Partials in Rails views — our card: how a partial exposes its API through locals and a yielded block
- 📄 Rails Guide: Using partials Show archive.org snapshot — the reference
ViewComponent
- 📄 ViewComponent: Overview Show archive.org snapshot , How-to guide Show archive.org snapshot and Best practices Show archive.org snapshot — the official documentation; read Overview and Best practices, use the guide as reference
- 📄 ViewComponent in the Wild I: building modern Rails frontends Show archive.org snapshot — Evil Martians, 2022; practical conventions from real projects
- 📄 Building reusable UI components in Rails with ViewComponent Show archive.org snapshot — a tutorial-style walkthrough if you prefer one
- ▶️ Arne's internal talk on ViewComponent (in our library; slides)
Exercises
1. Find the components in MovieDB
Go through your MovieDB views and identify the recurring pieces: cards, sections, buttons, the navigation, tabs, form rows. Extract them into partials and helpers.
The goal is that every view gets a nice, terse API to use a component without duplicating its HTML anywhere. Judge the result by reading the views afterwards: they need to look nice.
2. Turn partials into components
Convert some of your partials into ViewComponent components. Your MovieDB comes with view_component preconfigured and already contains example components — follow their style and conventions.
Aim for the same thing as before — a nice API for the views — and use the opportunity to co-locate each component with its helpers. Write a component spec for at least one of them.