Search code examples
ruby-on-railsview-components

Couldn't find a template file or inline render method for sub-component


Getting this error:

ViewComponent::TemplateError in Welcome#show
Couldn't find a template file or inline render method for FaqComponent::QuestionComponent.

Kind of stuck forever with this issue, not sure how to resolve it. Trying to render a simple component using view_component gem.

# app/components/faq_component.rb

class FaqComponent < ViewComponent::Base
  renders_many :questions, "QuestionComponent"

  class QuestionComponent < ViewComponent::Base
    attr_reader :question

    def initialize(question: "")
      @question = question
    end
  end
end

Now, template file looks like: file location: app/components/faq_component/faq_component.html.erb

<%= content_tag :div, class: "c-faq", data: { controller: "faq" } do %>
  <%= content_tag :div, class: "c-card" do %>
    <% questions.each do |q| %>
      <%= content_tag :div, class: "c-card__section" do %>
        <button class="c-faq__question" data-faq-target="question">
          <%= q.question %>
          <%= icon("arrow-expand", classes: "u-m-0", size: 12) %>
        </button>
        <div class="c-faq__answer">
          <%= q %> <!- IT'S GETTING ERROR HERE ->
        </div>
      <% end %>
    <% end %>
  <% end %>
<% end %>

And finally trying to render here:

    <div class="l-container u-mb-xxl u-xs-mb-l">
      <div class="l-row">
        <div class="l-col-xs-26 l-col-md-24 l-col-md-offset-1">
          <h3 class="u-mb-s">Common Questions</h3>
          <%= render(FaqComponent.new) do |faq| %>
            <% faq.question(question: "What is ViewComponent?") do %>
              <p>View component is a pain because it's not working or because I'm using it for the very first time!</p>
            <% end %>
          <% end %>
        </div>
      </div>
    </div>

Any help will highly appreciable! :bow


Solution

  • Have to define a template or call method for the QuestionComponent nested in the FaqComponent, that's the source of your errors.

    That's why it fails at <%= q %>, which is trying to render the QuestionComponent. If you add a app/components/faq_component/question_component.html.erb file that would likely resolve the issue.

    Maintainer replied here. Cheers!