3
0

ViewComponentについての備忘録

Posted at

ViewComponentってなんやねん

  • Rails 6.1 から標準で提供されるようになった
  • Reactから影響を受けた、Presenter(ViewのためのUIのビジネスロジックを書く)パターンの進化版
  • viewの再利用性を向上させるためのコンポーネントベースのアプローチ

パーシャルと何が違うの?

  • ViewComponent はパーシャルよりも独立したユニットとして扱われるため、コンポーネントごとにテストを書くことが簡単にできる

  • パーシャルより読み込みが早い = パフォーマンスが向上する
    従来のRailsテンプレートは実行時に読み込まれていたが、ViewComponentのテンプレートは、アプリケーション起動時にプリコンパイルされるため

  • コードの品質が高まる
    ViewComponentは単なるRubyのオブジェクトのため、コードの品質基準を守ることが比較的に容易

使い方

gemをインストール

gem "view_component"

基本的にrbファイルとerbファイルがセットで生成される。

rails g component コンポーネント名 引数

---

app/components/
├── コンポーネント名_component.html.erb
└── コンポーネント名_component.rb


例としてはこんな感じ。

# app/components/example_component.rb
class ExampleComponent < ViewComponent::Base
  def initialize(title:)
    @title = title
  end
end
<%# app/components/example_component.html.erb %>
<span title="<%= @title %>"><%= content %></span>
# 呼び出し元
<%= render(ExampleComponent.new(title: 'my title')) do %>
  Hello, World!
<% end %>
<!--出力結果-->
<span title="my title">Hello, World!</span>

app/components/example_component.rbだけでも表示することはできる

class ExampleComponent < ViewComponent::Base
  def initialize(url:)
    @url = url
  end

  def call
    button_to('削除', @url, method: :delete)
  end
end
<%= render ExampleComponent.new(url: xxxx_path) %>

ViewComponentではクラス内でcallメソッドを定義し、その中でビューをレンダリングするためのロジックが書かれてあるので、そこに表示したい内容を書くこともできる。

参考

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0