File: conditional_rendering.md

package info (click to toggle)
ruby-view-component 2.74.1-1
  • links: PTS, VCS
  • area: contrib
  • in suites: bookworm
  • size: 3,156 kB
  • sloc: ruby: 6,731; sh: 163; javascript: 10; makefile: 4
file content (56 lines) | stat: -rw-r--r-- 1,223 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
---
layout: default
title: Conditional rendering
parent: How-to guide
---

# Conditional rendering

Since 1.8.0
{: .label }

Components can implement a `#render?` method to be called after initialization to determine if the component should render.

Traditionally, the logic for whether to render a view could go in either the component template:

```erb
<% if user.requires_confirmation? %>
  <div class="alert">Please confirm your email address.</div>
<% end %>
```

or the view that renders the component:

```erb
<% if current_user.requires_confirmation? %>
  <%= render(ConfirmEmailComponent.new(user: current_user)) %>
<% end %>
```

Using the `#render?` hook simplifies the view:

```ruby
# app/components/confirm_email_component.rb
class ConfirmEmailComponent < ViewComponent::Base
  def initialize(user:)
    @user = user
  end

  def render?
    @user.requires_confirmation?
  end
end
```

```erb
<%# app/components/confirm_email_component.html.erb %>
<div class="banner">
  Please confirm your email address.
</div>
```

```erb
<%= render(ConfirmEmailComponent.new(user: current_user)) %>
```

_To assert that a component hasn't been rendered, use `refute_component_rendered` from `ViewComponent::TestHelpers`._